uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
8599636638e4059fcd3a13ac
train
function
@pytest.mark.skipif(SKIP_PUBLIC, reason=REASON) def test_read_ome_multi_image_pixels(): """Test read OME with three image series.""" fname = public_file('OME/bioformats-artificial/multi-image-pixels.ome.tif') with TiffFile(fname) as tif: assert tif.is_ome assert tif.byteorder == '>' ...
@pytest.mark.skipif(SKIP_PUBLIC, reason=REASON) def test_read_ome_multi_image_pixels():
"""Test read OME with three image series.""" fname = public_file('OME/bioformats-artificial/multi-image-pixels.ome.tif') with TiffFile(fname) as tif: assert tif.is_ome assert tif.byteorder == '>' assert len(tif.pages) == 86 assert len(tif.series) == 3 # assert page pr...
_multifile # assert data data = tif.asarray() assert isinstance(data, numpy.ndarray) assert data.shape == (10, 5, 200, 200) assert data.dtype == numpy.uint8 assert data[9, 4, 190, 192] == 92 assert_aszarr_method(tif, data) assert__str__(tif) @pytest.mark.s...
109
109
365
22
87
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_ome_multi_image_pixels
test_read_ome_multi_image_pixels
7,509
7,544
7,509
7,510
b76ce3fb5e0d59d682c4219a8bba073ca222d8da
bigcode/the-stack
train
e76672c79bf71713230f9130
train
function
@pytest.mark.skipif( SKIP_PRIVATE or SKIP_CODECS or not imagecodecs.JPEG, reason=REASON ) def test_issue_cr2_ojpeg(): """Test read OJPEG image from CR2.""" # https://github.com/cgohlke/tifffile/issues/75 fname = private_file('CanonCR2/Canon - EOS M6 - RAW (3 2).cr2') with TiffFile(fname) as tif: ...
@pytest.mark.skipif( SKIP_PRIVATE or SKIP_CODECS or not imagecodecs.JPEG, reason=REASON ) def test_issue_cr2_ojpeg():
"""Test read OJPEG image from CR2.""" # https://github.com/cgohlke/tifffile/issues/75 fname = private_file('CanonCR2/Canon - EOS M6 - RAW (3 2).cr2') with TiffFile(fname) as tif: assert len(tif.pages) == 4 page = tif.pages[0] assert page.compression == 6 assert page.sha...
assert series.axes == 'ZYX' assert series.shape == (10, 248, 260) assert series.get_axes(squeeze=False) == 'TZCYXS' assert series.get_shape(squeeze=False) == (1, 10, 1, 248, 260, 1) data = tif.asarray(squeeze=False) assert_array_equal(image, data) ...
150
150
502
37
113
bioturing/tifffile
tests/test_tifffile.py
Python
test_issue_cr2_ojpeg
test_issue_cr2_ojpeg
1,175
1,223
1,175
1,178
367a362b1bc6314f2e3cf71dcb62e3b2fde49f2e
bigcode/the-stack
train
4843fc6135aaafc9ebd861bf
train
function
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_geotiff_spaf27_markedcorrect(): """Test read GeoTIFF.""" fname = private_file('geotiff/spaf27_markedcorrect.tif') with TiffFile(fname) as tif: assert tif.is_geotiff assert tif.byteorder == '<' assert len(tif.pages) == 1 ...
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_geotiff_spaf27_markedcorrect():
"""Test read GeoTIFF.""" fname = private_file('geotiff/spaf27_markedcorrect.tif') with TiffFile(fname) as tif: assert tif.is_geotiff assert tif.byteorder == '<' assert len(tif.pages) == 1 assert len(tif.series) == 1 # assert series properties series = tif.seri...
0, 5900040.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0], ], ) assert_aszarr_method(page) assert__str__(tif) @pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_geotiff_spaf27_markedcorrect():
97
97
324
26
71
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_geotiff_spaf27_markedcorrect
test_read_geotiff_spaf27_markedcorrect
9,076
9,106
9,076
9,077
c2adb16bec1e1b756aec9c4d7ff0d97637961881
bigcode/the-stack
train
971982332f637ecdeda2c71b
train
function
@pytest.mark.skipif( SKIP_PUBLIC or SKIP_CODECS or not imagecodecs.LJPEG, reason=REASON ) def test_read_cfa(): """Test read 14-bit uncompressed and JPEG compressed CFA image.""" fname = private_file('DNG/cinemadng/M14-1451_000085_cDNG_uncompressed.dng') with TiffFile(fname) as tif: assert len(ti...
@pytest.mark.skipif( SKIP_PUBLIC or SKIP_CODECS or not imagecodecs.LJPEG, reason=REASON ) def test_read_cfa():
"""Test read 14-bit uncompressed and JPEG compressed CFA image.""" fname = private_file('DNG/cinemadng/M14-1451_000085_cDNG_uncompressed.dng') with TiffFile(fname) as tif: assert len(tif.pages) == 1 page = tif.pages[0] assert page.compression == 1 assert page.photometric == C...
assert page.bitspersample == 16 assert page.tags['CFARepeatPatternDim'].value == (2, 2) assert page.tags['CFAPattern'].value == b'\x00\x01\x01\x02' data = page.asarray() assert_aszarr_method(tif.series[1], data) assert__str__(tif) @pytest.mark.skipif( SKIP_PUBLIC or S...
113
113
378
34
79
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_cfa
test_read_cfa
5,144
5,176
5,144
5,147
33d6a845341c587c8c6bdc73cf2533bd814536b3
bigcode/the-stack
train
aa21744719fbe138f1fed379
train
function
@pytest.mark.skipif(SKIP_PUBLIC or SKIP_CODECS, reason=REASON) def test_read_jello(): """Test read 256x192x3, uint16, palette, PackBits.""" fname = public_file('juicypixels/jello.tif') with TiffFile(fname) as tif: assert tif.byteorder == '>' assert len(tif.pages) == 1 assert len(tif....
@pytest.mark.skipif(SKIP_PUBLIC or SKIP_CODECS, reason=REASON) def test_read_jello():
"""Test read 256x192x3, uint16, palette, PackBits.""" fname = public_file('juicypixels/jello.tif') with TiffFile(fname) as tif: assert tif.byteorder == '>' assert len(tif.pages) == 1 assert len(tif.series) == 1 # assert page properties page = tif.pages[0] asse...
isinstance(data, numpy.ndarray) assert data.flags['C_CONTIGUOUS'] assert data.shape == (607, 800) assert data.dtype == numpy.uint8 assert data[273, 426] == 34 assert_aszarr_method(tif, data) assert__str__(tif) @pytest.mark.skipif(SKIP_PUBLIC or SKIP_CODECS, reason=REASON...
93
93
312
24
69
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_jello
test_read_jello
4,178
4,207
4,178
4,179
ebda6eb53b32e84ca2411a59105d39c374b74750
bigcode/the-stack
train
a209ab1a2facbc76ee1210c1
train
function
def assert_valid_tiff(filename, *args, **kwargs): """Validate TIFF file using jhove script.""" if SKIP_VALIDATE: return validate_jhove(filename, 'jhove.cmd', *args, **kwargs)
def assert_valid_tiff(filename, *args, **kwargs):
"""Validate TIFF file using jhove script.""" if SKIP_VALIDATE: return validate_jhove(filename, 'jhove.cmd', *args, **kwargs)
+ 1): TiffFile.__str__(tif, detail=i) def assert_valid_omexml(omexml): """Validate OME-XML schema.""" OmeXml.validate(omexml, assert_=True) def assert_valid_tiff(filename, *args, **kwargs):
64
64
51
13
51
bioturing/tifffile
tests/test_tifffile.py
Python
assert_valid_tiff
assert_valid_tiff
336
340
336
336
a1e482391ff80e3cdc5aeee0af11eadb062fcc33
bigcode/the-stack
train
3059c8e06c50e048c71d41da
train
function
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_geotiff_dimapdocument(): """Test read GeoTIFF with 43 MB XML tag value.""" # tag 65000 45070067s @487 "<Dimap_Document... fname = private_file('geotiff/DimapDocument.tif') with TiffFile(fname) as tif: assert tif.is_geotiff ...
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_geotiff_dimapdocument():
"""Test read GeoTIFF with 43 MB XML tag value.""" # tag 65000 45070067s @487 "<Dimap_Document... fname = private_file('geotiff/DimapDocument.tif') with TiffFile(fname) as tif: assert tif.is_geotiff assert tif.byteorder == '>' assert len(tif.pages) == 1 assert len(tif.se...
provided by Marco Oster on 10/26/2016 fname = private_file('tvips/test_tietz_16bit.tif') with TiffFile(fname) as tif: assert tif.is_tvips tvips = tif.tvips_metadata assert tvips['Magic'] == 0xAAAAAAAA assert tvips['ImageFolder'] == 'B:\\4Marco\\Images\\Tiling_EMTOOLS\\' ...
133
133
444
23
110
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_geotiff_dimapdocument
test_read_geotiff_dimapdocument
9,034
9,073
9,034
9,035
a022bd0bda69334e035bf31f7608319312d4bbab
bigcode/the-stack
train
235f3367198f28f61aacd5bc
train
function
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_metaseries_g4d7r(): """Test read Metamorph/Metaseries.""" # 12113x13453, uint16 fname = private_file('metaseries/g4d7r.tif') with TiffFile(fname) as tif: assert tif.byteorder == '<' assert len(tif.pages) == 1 assert l...
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_metaseries_g4d7r():
"""Test read Metamorph/Metaseries.""" # 12113x13453, uint16 fname = private_file('metaseries/g4d7r.tif') with TiffFile(fname) as tif: assert tif.byteorder == '<' assert len(tif.pages) == 1 assert len(tif.series) == 1 assert tif.is_metaseries # assert page properti...
2) assert series.dtype == numpy.uint16 assert series.axes == 'YX' # assert data data = tif.asarray() assert data.shape == (1040, 1392) assert data.dtype == numpy.uint16 assert data[256, 256] == 1917 assert_aszarr_method(series, data) assert_aszarr_...
124
124
415
25
99
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_metaseries_g4d7r
test_read_metaseries_g4d7r
8,807
8,845
8,807
8,808
ea846c44116dd59352de7bcf0a7c1dc3617ffef2
bigcode/the-stack
train
6409b886095f795c115a3516
train
function
def test_write_scalar_4d(): """Test write 4D grayscale.""" data = random_data(numpy.uint8, (3, 2, 219, 301)) with TempFileName('scalar_4d') as fname: imwrite(fname, data) assert_valid_tiff(fname) with TiffFile(fname) as tif: assert len(tif.pages) == 6 page = t...
def test_write_scalar_4d():
"""Test write 4D grayscale.""" data = random_data(numpy.uint8, (3, 2, 219, 301)) with TempFileName('scalar_4d') as fname: imwrite(fname, data) assert_valid_tiff(fname) with TiffFile(fname) as tif: assert len(tif.pages) == 6 page = tif.pages[5] asse...
ength == 219 assert page.samplesperpixel == 1 image = tif.asarray() assert isinstance(image, numpy.ndarray) assert_array_equal(data, image) assert_aszarr_method(tif, image) assert__str__(tif) def test_write_scalar_4d():
64
64
183
8
56
bioturing/tifffile
tests/test_tifffile.py
Python
test_write_scalar_4d
test_write_scalar_4d
11,707
11,725
11,707
11,707
cd8a8b7fefb641b6aa57723636dd86c74d49ff14
bigcode/the-stack
train
4b2d51d68b276664f0561299
train
function
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_issue_extra_strips(caplog): """Test read extra strips.""" # https://github.com/opencv/opencv/issues/17054 with TiffFile(private_file('issues/extra_strips.tif')) as tif: assert not tif.is_bigtiff assert len(tif.pages) == 1 page...
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_issue_extra_strips(caplog):
"""Test read extra strips.""" # https://github.com/opencv/opencv/issues/17054 with TiffFile(private_file('issues/extra_strips.tif')) as tif: assert not tif.is_bigtiff assert len(tif.pages) == 1 page = tif.pages[0] assert page.tags['StripOffsets'].value == (8, 0, 0) as...
# assert data image = page.asrgb() assert image.shape == (32, 32, 3) assert_aszarr_method(page) del image assert__str__(tif) @pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_issue_extra_strips(caplog):
69
69
231
22
47
bioturing/tifffile
tests/test_tifffile.py
Python
test_issue_extra_strips
test_issue_extra_strips
662
680
662
663
7ecced9e82f2a90abae2cedcc485cbc2481313de
bigcode/the-stack
train
ae57d0740f6b4fbd3c0526a7
train
function
def assert_decode_method(page, image=None): """Call TiffPage.decode on all segments and compare to TiffPage.asarray.""" fh = page.parent.filehandle if page.is_tiled: offsets = page.tags['TileOffsets'].value bytecounts = page.tags['TileByteCounts'].value else: offsets = page.tags[...
def assert_decode_method(page, image=None):
"""Call TiffPage.decode on all segments and compare to TiffPage.asarray.""" fh = page.parent.filehandle if page.is_tiled: offsets = page.tags['TileOffsets'].value bytecounts = page.tags['TileByteCounts'].value else: offsets = page.tags['StripOffsets'].value bytecounts = p...
assert_=True) def assert_valid_tiff(filename, *args, **kwargs): """Validate TIFF file using jhove script.""" if SKIP_VALIDATE: return validate_jhove(filename, 'jhove.cmd', *args, **kwargs) def assert_decode_method(page, image=None):
64
64
176
9
55
bioturing/tifffile
tests/test_tifffile.py
Python
assert_decode_method
assert_decode_method
343
358
343
343
c63c6abc21868a7ba3b9f0f65502a471c347fef4
bigcode/the-stack
train
f5b485012fc64fd91d9a23d5
train
function
@pytest.mark.skipif(SKIP_PRIVATE or SKIP_CODECS or SKIP_LARGE, reason=REASON) def test_read_gel_scan(): """Test read 6976x4992x3 uint8 LZW.""" fname = private_file('large/gel_1-scan2.tif') with TiffFile(fname) as tif: assert tif.byteorder == '<' assert len(tif.pages) == 1 assert len(...
@pytest.mark.skipif(SKIP_PRIVATE or SKIP_CODECS or SKIP_LARGE, reason=REASON) def test_read_gel_scan():
"""Test read 6976x4992x3 uint8 LZW.""" fname = private_file('large/gel_1-scan2.tif') with TiffFile(fname) as tif: assert tif.byteorder == '<' assert len(tif.pages) == 1 assert len(tif.series) == 1 # assert page properties page = tif.pages[0] assert page.photom...
, 6000) assert data.dtype == numpy.int16 assert data[5199, 5107] == 1019 assert data[0, 0] == -32768 assert_aszarr_method(tif, data) del data assert__str__(tif) @pytest.mark.skipif(SKIP_PRIVATE or SKIP_CODECS or SKIP_LARGE, reason=REASON) def test_read_gel_scan():
97
97
326
30
67
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_gel_scan
test_read_gel_scan
5,562
5,592
5,562
5,563
5a17dd533e781edf25368c045947e69fd5662cc7
bigcode/the-stack
train
a888ada21eff7fed88b06cc9
train
function
@pytest.mark.skipif(SKIP_PUBLIC or SKIP_CODECS, reason=REASON) def test_read_hopper_2bit(): """Test read 2-bit, fillorder=lsb2msb.""" # https://github.com/python-pillow/Pillow/pull/1789 fname = public_file('pillow/tiff_gray_2_4_bpp/hopper2.tif') with TiffFile(fname) as tif: assert tif.byteorder ...
@pytest.mark.skipif(SKIP_PUBLIC or SKIP_CODECS, reason=REASON) def test_read_hopper_2bit():
"""Test read 2-bit, fillorder=lsb2msb.""" # https://github.com/python-pillow/Pillow/pull/1789 fname = public_file('pillow/tiff_gray_2_4_bpp/hopper2.tif') with TiffFile(fname) as tif: assert tif.byteorder == '<' assert len(tif.pages) == 1 assert len(tif.series) == 1 # asse...
_decode_method(page, data) assert_aszarr_method(page, data) assert__str__(tif) @pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_exif_paint(): """Test read EXIF tags.""" fname = private_file('exif/paint.tif') with TiffFile(fname) as tif: exif = tif.pages[0].tags['ExifT...
174
174
583
27
147
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_hopper_2bit
test_read_hopper_2bit
3,683
3,738
3,683
3,684
53ad10d92d7bcc8336185799df4903badb5ef330
bigcode/the-stack
train
04169c4e693644977334893c
train
function
@pytest.mark.parametrize('subfiletype', [0b1, 0b10, 0b100, 0b1000, 0b1111]) def test_write_subfiletype(subfiletype): """Test write subfiletype.""" data = random_data(numpy.uint8, (16, 16)) if subfiletype & 0b100: data = data.astype('bool') with TempFileName(f'subfiletype_{subfiletype}') as fname...
@pytest.mark.parametrize('subfiletype', [0b1, 0b10, 0b100, 0b1000, 0b1111]) def test_write_subfiletype(subfiletype):
"""Test write subfiletype.""" data = random_data(numpy.uint8, (16, 16)) if subfiletype & 0b100: data = data.astype('bool') with TempFileName(f'subfiletype_{subfiletype}') as fname: imwrite(fname, data, subfiletype=subfiletype) assert_valid_tiff(fname) with TiffFile(fname)...
assert tuple(tags['34567'].value) == (value,) * 4 assert__str__(tif) @pytest.mark.parametrize('subfiletype', [0b1, 0b10, 0b100, 0b1000, 0b1111]) def test_write_subfiletype(subfiletype):
71
71
238
45
26
bioturing/tifffile
tests/test_tifffile.py
Python
test_write_subfiletype
test_write_subfiletype
10,374
10,391
10,374
10,375
8896862a7fc283456c489418121eb845c4f77abf
bigcode/the-stack
train
254d55a6efbe57d96d8a70a3
train
function
def assert__str__(tif, detail=3): """Call the TiffFile.__str__ function.""" for i in range(detail + 1): TiffFile.__str__(tif, detail=i)
def assert__str__(tif, detail=3):
"""Call the TiffFile.__str__ function.""" for i in range(detail + 1): TiffFile.__str__(tif, detail=i)
TiffFile.""" for flag in FILE_FLAGS: getattr(tiff_file, flag) def assert_page_flags(tiff_page): """Access all flags of TiffPage.""" for flag in PAGE_FLAGS: getattr(tiff_page, flag) def assert__str__(tif, detail=3):
64
64
47
12
52
bioturing/tifffile
tests/test_tifffile.py
Python
assert__str__
assert__str__
325
328
325
325
dde9c2f0ae9559cf6227d55b8e7ee9e8d38d5a30
bigcode/the-stack
train
14a1f7a7b10cbc2e20171d76
train
function
@pytest.mark.skipif( SKIP_PRIVATE or SKIP_CODECS or not imagecodecs.JPEG or SKIP_LARGE, reason=REASON, ) def test_write_ome_copy(): """Test write pyramidal OME-TIFF by copying compressed tiles from SVS.""" def tiles(page): # return iterator over compressed tiles in page assert page.is_t...
@pytest.mark.skipif( SKIP_PRIVATE or SKIP_CODECS or not imagecodecs.JPEG or SKIP_LARGE, reason=REASON, ) def test_write_ome_copy():
"""Test write pyramidal OME-TIFF by copying compressed tiles from SVS.""" def tiles(page): # return iterator over compressed tiles in page assert page.is_tiled fh = page.parent.filehandle for offset, bytecount in zip(page.dataoffsets, page.databytecounts): fh.seek(of...
21, 1), axes='CYX' ) tif.overwrite_description(xml.tostring()) with TiffFile(fname) as tif: assert tif.is_ome assert len(tif.pages) == 19 assert len(tif.series) == 2 # assert series properties series = tif.series[0] ...
211
211
704
41
170
bioturing/tifffile
tests/test_tifffile.py
Python
test_write_ome_copy
test_write_ome_copy
13,649
13,728
13,649
13,653
fa946cb5ac323ba5d187337f64055bbe71d71662
bigcode/the-stack
train
caae5f27db3086cdd245450e
train
function
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_nih_morph(): """Test read NIH.""" # 388x252 uint8 fname = private_file('nihimage/morph.tiff') with TiffFile(fname) as tif: assert tif.is_nih assert tif.byteorder == '>' assert len(tif.pages) == 1 assert len(ti...
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_nih_morph():
"""Test read NIH.""" # 388x252 uint8 fname = private_file('nihimage/morph.tiff') with TiffFile(fname) as tif: assert tif.is_nih assert tif.byteorder == '>' assert len(tif.pages) == 1 assert len(tif.series) == 1 # assert page properties page = tif.pages[0] ...
512, 512) assert data.dtype == numpy.uint16 assert round(abs(data[50, 256, 256] - 703), 7) == 0 assert_aszarr_method(tif, data) assert_aszarr_method(tif, data, chunkmode='page') assert__str__(tif, 0) @pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_nih_morph():
98
98
329
21
77
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_nih_morph
test_read_nih_morph
8,090
8,124
8,090
8,091
1eb15786a6dfedcf7e014e9eaf92d4ffe10355ca
bigcode/the-stack
train
2f5d641b2164f5ab64c48b9c
train
function
@pytest.mark.skipif(SKIP_LARGE, reason=REASON) def test_write_imagej_raw(): """Test write ImageJ 5 GB raw file.""" data = numpy.empty((1280, 1, 1024, 1024), dtype=numpy.float32) data[:] = numpy.arange(1280, dtype=numpy.float32).reshape(-1, 1, 1, 1) with TempFileName('imagej_big') as fname: with...
@pytest.mark.skipif(SKIP_LARGE, reason=REASON) def test_write_imagej_raw():
"""Test write ImageJ 5 GB raw file.""" data = numpy.empty((1280, 1, 1024, 1024), dtype=numpy.float32) data[:] = numpy.arange(1280, dtype=numpy.float32).reshape(-1, 1, 1, 1) with TempFileName('imagej_big') as fname: with pytest.warns(UserWarning): # UserWarning: truncating ImageJ fil...
, 256) assert series.dtype == numpy.uint8 assert series.axes == 'ZYX' assert series.get_axes(False) == 'TZCYXS' assert series.get_shape(False) == (1, 256, 1, 256, 256, 1) # assert data image = tif.asarray(out='memmap') assert_array_equa...
118
118
394
21
97
bioturing/tifffile
tests/test_tifffile.py
Python
test_write_imagej_raw
test_write_imagej_raw
13,344
13,380
13,344
13,345
ed29bc3a6384fa6c2f3e78f4966d4670466db31c
bigcode/the-stack
train
278cdbfd37dcee77fabde852
train
function
def test_write_append_nontif(): """Test fail to append to non-TIFF file.""" with TempFileName('append_nontif.bin') as fname: with open(fname, 'wb') as fh: fh.write(b'not a TIFF file') with pytest.raises(TiffFileError): with TiffWriter(fname, append=True): ...
def test_write_append_nontif():
"""Test fail to append to non-TIFF file.""" with TempFileName('append_nontif.bin') as fname: with open(fname, 'wb') as fh: fh.write(b'not a TIFF file') with pytest.raises(TiffFileError): with TiffWriter(fname, append=True): pass
_tiff(fname) def test_write_append_not_exists(): """Test append to non existing file.""" with TempFileName('append_not_exists.bin') as fname: # with self.assertRaises(ValueError): with TiffWriter(fname, append=True): pass def test_write_append_nontif():
64
64
78
8
55
bioturing/tifffile
tests/test_tifffile.py
Python
test_write_append_nontif
test_write_append_nontif
10,037
10,044
10,037
10,037
8eb07a016845802929805c3442b9a058293a5ef6
bigcode/the-stack
train
8fbf6250f05ce9adccd6c390
train
function
@pytest.mark.skipif(SKIP_PRIVATE or SKIP_CODECS or SKIP_LARGE, reason=REASON) def test_read_ome_corrupted_page(caplog): """Test read OME with corrupted but not referenced page.""" # https://forum.image.sc/t/qupath-0-2-0-not-able-to-open-ome-tiff/23821/3 fname = private_file('ome/2019_02_19__7760_s1.ome.tiff...
@pytest.mark.skipif(SKIP_PRIVATE or SKIP_CODECS or SKIP_LARGE, reason=REASON) def test_read_ome_corrupted_page(caplog):
"""Test read OME with corrupted but not referenced page.""" # https://forum.image.sc/t/qupath-0-2-0-not-able-to-open-ome-tiff/23821/3 fname = private_file('ome/2019_02_19__7760_s1.ome.tiff') with TiffFile(fname) as tif: assert tif.is_ome assert tif.is_bigtiff assert tif.byteorder...
249, 324) assert data.dtype == numpy.uint16 assert data[4, 9, 1, 175, 123] == 9605 assert_aszarr_method(tif, data) assert_aszarr_method(tif, data, chunkmode='page') del data assert__str__(tif) @pytest.mark.skipif(SKIP_PRIVATE or SKIP_CODECS or SKIP_LARGE, reason=REASON) ...
111
111
372
34
77
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_ome_corrupted_page
test_read_ome_corrupted_page
7,862
7,893
7,862
7,863
2352a21ce2a99dd78ae93fd8d3dfc2bda5b2202d
bigcode/the-stack
train
a59c4e24d0c1905a4969a696
train
function
@pytest.mark.skipif(SKIP_CODECS or not imagecodecs.JPEGXL, reason=REASON) def test_write_compression_jpegxl(): """Test write JPEG XL compression.""" data = WRITE_DATA.astype(numpy.uint8).reshape((219, 301, 3)) with TempFileName('compression_jpegxl') as fname: imwrite(fname, data, compression=(JPEGXL...
@pytest.mark.skipif(SKIP_CODECS or not imagecodecs.JPEGXL, reason=REASON) def test_write_compression_jpegxl():
"""Test write JPEG XL compression.""" data = WRITE_DATA.astype(numpy.uint8).reshape((219, 301, 3)) with TempFileName('compression_jpegxl') as fname: imwrite(fname, data, compression=(JPEGXL, -1), photometric=RGB) assert_valid_tiff(fname) with TiffFile(fname) as tif: asser...
image = tif.asarray() assert_array_equal(data, image) assert_aszarr_method(tif, image) assert__str__(tif) @pytest.mark.skipif(SKIP_CODECS or not imagecodecs.JPEGXL, reason=REASON) def test_write_compression_jpegxl():
65
65
217
31
34
bioturing/tifffile
tests/test_tifffile.py
Python
test_write_compression_jpegxl
test_write_compression_jpegxl
10,898
10,917
10,898
10,899
a3add4c7d0244113012372d40fbc1c18fd9fd937
bigcode/the-stack
train
82bda25a7dfdec27a6162de3
train
function
@pytest.mark.skipif(SKIP_PRIVATE or SKIP_CODECS, reason=REASON) def test_issue_palette_with_extrasamples(): """Test read palette with extra samples.""" # https://github.com/python-pillow/Pillow/issues/1597 fname = private_file('issues/palette_with_extrasamples.tif') with TiffFile(fname) as tif: ...
@pytest.mark.skipif(SKIP_PRIVATE or SKIP_CODECS, reason=REASON) def test_issue_palette_with_extrasamples():
"""Test read palette with extra samples.""" # https://github.com/python-pillow/Pillow/issues/1597 fname = private_file('issues/palette_with_extrasamples.tif') with TiffFile(fname) as tif: assert len(tif.pages) == 1 page = tif.pages[0] assert page.photometric == PALETTE as...
RGB) with TiffFile(fname) as tif: tags = tif.pages[0].tags 'SampleFormat' not in tags assert tags['ExtraSamples'].value == (2,) assert__str__(tif) @pytest.mark.skipif(SKIP_PRIVATE or SKIP_CODECS, reason=REASON) def test_issue_palette_with_extrasamples():
78
78
261
27
51
bioturing/tifffile
tests/test_tifffile.py
Python
test_issue_palette_with_extrasamples
test_issue_palette_with_extrasamples
610
634
610
611
56ccc1920f1913ffd2c3f481db7f34269c7798f7
bigcode/the-stack
train
c61ae42d4197f9420313ed69
train
function
def test_issue_imagej_singlet_dimensions(): """Test that ImageJ files can be read preserving singlet dimensions.""" # https://github.com/cgohlke/tifffile/issues/19 # https://github.com/cgohlke/tifffile/issues/66 data = numpy.random.randint( 0, 2**8, (1, 10, 1, 248, 260, 1), numpy.uint8 ) ...
def test_issue_imagej_singlet_dimensions():
"""Test that ImageJ files can be read preserving singlet dimensions.""" # https://github.com/cgohlke/tifffile/issues/19 # https://github.com/cgohlke/tifffile/issues/66 data = numpy.random.randint( 0, 2**8, (1, 10, 1, 248, 260, 1), numpy.uint8 ) with TempFileName('issue_imagej_singlet_d...
from pickle import dumps, loads assert loads(dumps(TIFF)).CHUNKMODE.PLANE == TIFF.CHUNKMODE.PLANE assert loads(dumps(TIFF.CHUNKMODE)).PLANE == TIFF.CHUNKMODE.PLANE assert loads(dumps(TIFF.CHUNKMODE.PLANE)) == TIFF.CHUNKMODE.PLANE def test_issue_imagej_singlet_dimensions():
85
85
286
10
74
bioturing/tifffile
tests/test_tifffile.py
Python
test_issue_imagej_singlet_dimensions
test_issue_imagej_singlet_dimensions
1,148
1,172
1,148
1,148
96d0e75261eb7ef376ec2d9db34423532281e0dc
bigcode/the-stack
train
83cf03f423cb21aeed6078c0
train
function
def test_write_software_tag(): """Test write Software tag.""" data = random_data(numpy.uint8, (2, 219, 301)) software = 'test_tifffile.py' with TempFileName('software_tag') as fname: imwrite(fname, data, software=software) assert_valid_tiff(fname) with TiffFile(fname) as tif: ...
def test_write_software_tag():
"""Test write Software tag.""" data = random_data(numpy.uint8, (2, 219, 301)) software = 'test_tifffile.py' with TempFileName('software_tag') as fname: imwrite(fname, data, software=software) assert_valid_tiff(fname) with TiffFile(fname) as tif: assert len(tif.pages) ...
if.pages) == 2 assert tif.pages[0].description == description assert 'ImageDescription' not in tif.pages[1].tags assert 'ImageDescription1' not in tif.pages[0].tags assert__str__(tif) def test_write_software_tag():
64
64
128
7
57
bioturing/tifffile
tests/test_tifffile.py
Python
test_write_software_tag
test_write_software_tag
10,453
10,464
10,453
10,453
27e4a0d1f6b3afe89be38b544d6b8ab77c8c0516
bigcode/the-stack
train
0b910864fe07d05ee00280ef
train
function
@pytest.mark.skipif(SKIP_PRIVATE or SKIP_LARGE, reason=REASON) def test_func_lsm2bin(): """Test lsm2bin function.""" # Convert LSM to BIN fname = private_file( 'lsm/Twoareas_Zstacks54slices_3umintervals_5cycles.lsm' ) # fname = private_file( # 'LSM/fish01-wt-t01-10_ForTest-20zplanes1...
@pytest.mark.skipif(SKIP_PRIVATE or SKIP_LARGE, reason=REASON) def test_func_lsm2bin():
"""Test lsm2bin function.""" # Convert LSM to BIN fname = private_file( 'lsm/Twoareas_Zstacks54slices_3umintervals_5cycles.lsm' ) # fname = private_file( # 'LSM/fish01-wt-t01-10_ForTest-20zplanes10timepoints.lsm') lsm2bin(fname, '', verbose=True)
_FORMAT> ... <BAND_INDEX>0</BAND_INDEX> </Spectral_Band_Info> </Image_Interpretation> </Dimap_Document>""" ) @pytest.mark.skipif(SKIP_PRIVATE or SKIP_LARGE, reason=REASON) def test_func_lsm2bin():
64
64
120
26
38
bioturing/tifffile
tests/test_tifffile.py
Python
test_func_lsm2bin
test_func_lsm2bin
3,194
3,203
3,194
3,195
4b50643ced4369f64b7624b024b4bb59525141d9
bigcode/the-stack
train
b444a481d005a3d8dbe91ccf
train
function
@pytest.mark.skipif(SKIP_PRIVATE or SKIP_LARGE, reason=REASON) def test_read_stk_112508h100(): """Test read MetaMorph STK large time-series.""" fname = private_file('stk/112508h100.stk') with TiffFile(fname) as tif: assert tif.is_stk assert tif.byteorder == '<' assert len(tif.pages) ...
@pytest.mark.skipif(SKIP_PRIVATE or SKIP_LARGE, reason=REASON) def test_read_stk_112508h100():
"""Test read MetaMorph STK large time-series.""" fname = private_file('stk/112508h100.stk') with TiffFile(fname) as tif: assert tif.is_stk assert tif.byteorder == '<' assert len(tif.pages) == 1 assert len(tif.series) == 1 # assert page properties page = tif.pa...
2, 480, 640) assert series.dtype == numpy.uint8 assert series.axes == 'IYX' # assert data data = tif.asarray() assert isinstance(data, numpy.ndarray) assert data.shape == (2, 480, 640) assert data.dtype == numpy.uint8 assert data[1, 339, 579] == 56 ...
132
132
440
29
103
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_stk_112508h100
test_read_stk_112508h100
6,450
6,491
6,450
6,451
dd20f393df831dea7ed1c277f1b16819a4ba9cf4
bigcode/the-stack
train
087080d1aeece78348c14316
train
function
@pytest.mark.skipif(SKIP_PRIVATE or SKIP_LARGE or SKIP_CODECS, reason=REASON) def test_sequence_wells_axesorder(): """Test FileSequence with well plates and axes reorder.""" # https://bbbc.broadinstitute.org/BBBC006 categories = {'p': {chr(i + 97): i for i in range(25)}} ptrn = r'(?:_(z)_(\d+)).*_(?P<p>...
@pytest.mark.skipif(SKIP_PRIVATE or SKIP_LARGE or SKIP_CODECS, reason=REASON) def test_sequence_wells_axesorder():
"""Test FileSequence with well plates and axes reorder.""" # https://bbbc.broadinstitute.org/BBBC006 categories = {'p': {chr(i + 97): i for i in range(25)}} ptrn = r'(?:_(z)_(\d+)).*_(?P<p>[a-z])(?P<a>\d+)(?:_(s)(\d))(?:_(w)(\d))' fnames = private_file('BBBC/BBBC006_v1_images_z_00/*.tif') fnames...
ifs.axes == 'I' data = tifs.asarray() assert isinstance(data, numpy.ndarray) assert data.flags['C_CONTIGUOUS'] assert data.shape == (10, 480, 640) assert data.dtype == numpy.uint8 assert data[9, 256, 256] == 135 assert_array_equal(data, imread(container=fname)) @pytes...
114
114
380
31
83
bioturing/tifffile
tests/test_tifffile.py
Python
test_sequence_wells_axesorder
test_sequence_wells_axesorder
14,135
14,157
14,135
14,136
afeeac2b607438c33e8018b4e13af0fab9fa9fd2
bigcode/the-stack
train
4b89f87acbc2a0f2ec92207a
train
function
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_issue_mmap(): """Test reading from mmap object with no readinto function..""" fname = public_file('OME/bioformats-artificial/4D-series.ome.tiff') with open(fname, 'rb') as fh: mm = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as...
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_issue_mmap():
"""Test reading from mmap object with no readinto function..""" fname = public_file('OME/bioformats-artificial/4D-series.ome.tiff') with open(fname, 'rb') as fh: mm = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) assert_array_equal(imread(mm), imread(fname)) mm.close()
_array_equal(page.asarray(), separate) page = tif.pages[2] assert page.photometric == SEPARATED assert page.extrasamples == (1,) assert_array_equal(page.asarray(), extrasample) @pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_issue_mmap():
64
64
101
19
45
bioturing/tifffile
tests/test_tifffile.py
Python
test_issue_mmap
test_issue_mmap
1,104
1,111
1,104
1,105
01bf61b7e2016f39d1970900c6e4f4e48bc29188
bigcode/the-stack
train
1536962683aff9c88856adee
train
function
def test_class_omexml_attributes(): """Test OmeXml class with attributes and elements.""" from uuid import uuid1 # noqa: delayed import uuid = str(uuid1()) metadata = dict( # document UUID=uuid, Creator=f'test_tifffile.py {tifffile.__version__}', # image axes='Z...
def test_class_omexml_attributes():
"""Test OmeXml class with attributes and elements.""" from uuid import uuid1 # noqa: delayed import uuid = str(uuid1()) metadata = dict( # document UUID=uuid, Creator=f'test_tifffile.py {tifffile.__version__}', # image axes='ZYXS', Name='ImageName', ...
Xml class with modulo dimensions.""" dtype = numpy.uint8 omexml = OmeXml() omexml.addimage(dtype, shape, storedshape, axes=axes) assert '\n ' in str(omexml) omexml = omexml.tostring() assert dimorder in omexml for ax, size in zip('TZC', sizetzc): assert f'Size{ax}="{size}"' in omexm...
124
124
414
9
115
bioturing/tifffile
tests/test_tifffile.py
Python
test_class_omexml_attributes
test_class_omexml_attributes
2,228
2,267
2,228
2,228
c3f4bc2dd793f6bff898888731e762892b1de1e0
bigcode/the-stack
train
3ce4826493b7da6aa50bc74c
train
function
@pytest.mark.skipif(SKIP_PRIVATE or SKIP_CODECS, reason=REASON) def test_read_quad_lzw_le(): """Test read 384x512 RGB uint8 LZW.""" fname = private_file('quad-lzw_le.tif') with TiffFile(fname) as tif: assert tif.byteorder == '<' assert len(tif.pages) == 1 assert len(tif.series) == 1 ...
@pytest.mark.skipif(SKIP_PRIVATE or SKIP_CODECS, reason=REASON) def test_read_quad_lzw_le():
"""Test read 384x512 RGB uint8 LZW.""" fname = private_file('quad-lzw_le.tif') with TiffFile(fname) as tif: assert tif.byteorder == '<' assert len(tif.pages) == 1 assert len(tif.series) == 1 # assert page properties page = tif.pages[0] assert page.photometric ...
assert data.flags['C_CONTIGUOUS'] assert data.shape == (384, 512, 3) assert data.dtype == numpy.uint8 assert tuple(data[309, 460, :]) == (0, 163, 187) assert_aszarr_method(tif, data) @pytest.mark.skipif(SKIP_PRIVATE or SKIP_CODECS, reason=REASON) def test_read_quad_lzw_le():
92
92
309
26
66
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_quad_lzw_le
test_read_quad_lzw_le
4,242
4,272
4,242
4,243
7b727c356bf1d3886d13cbb161340fad44798fbd
bigcode/the-stack
train
a3083fa234afe71ce59f1209
train
function
def private_file(pathname, base=PRIVATE_DIR, expand=True): """Return path to private test file(s).""" return data_file(pathname, base, expand=expand)
def private_file(pathname, base=PRIVATE_DIR, expand=True):
"""Return path to private test file(s).""" return data_file(pathname, base, expand=expand)
expand=True): """Return path to test file(s).""" path = os.path.join(base, *pathname.split('/')) if expand and any(i in path for i in '*?'): return glob.glob(path) return path def private_file(pathname, base=PRIVATE_DIR, expand=True):
64
64
38
14
49
bioturing/tifffile
tests/test_tifffile.py
Python
private_file
private_file
293
295
293
293
4b8ec57b79a5f4499950a562293ed32be7681810
bigcode/the-stack
train
8ac67e70aed99f9e66d0775e
train
function
@pytest.mark.skipif(SKIP_PUBLIC or SKIP_WIN, reason=REASON) def test_filehandle_unc_path(): """Test FileHandle from UNC path.""" with FileHandle(r'\\localhost\Data\Data\test_FileHandle.bin') as fh: assert fh.name == 'test_FileHandle.bin' assert fh.dirname == '\\\\localhost\\Data\\Data' a...
@pytest.mark.skipif(SKIP_PUBLIC or SKIP_WIN, reason=REASON) def test_filehandle_unc_path():
"""Test FileHandle from UNC path.""" with FileHandle(r'\\localhost\Data\Data\test_FileHandle.bin') as fh: assert fh.name == 'test_FileHandle.bin' assert fh.dirname == '\\\\localhost\\Data\\Data' assert_filehandle(fh)
fh.open() assert not fh.closed assert fh.is_file assert fh.name == 'test_FileHandle.bin' assert_filehandle(fh) finally: fh.close() @pytest.mark.skipif(SKIP_PUBLIC or SKIP_WIN, reason=REASON) def test_filehandle_unc_path():
64
64
83
24
40
bioturing/tifffile
tests/test_tifffile.py
Python
test_filehandle_unc_path
test_filehandle_unc_path
3,559
3,565
3,559
3,560
dc4a9cde30223fb3f9bd94bc19aab5d0e76d9425
bigcode/the-stack
train
13d2447caba6a8a1d8fa0654
train
function
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_sis(): """Test read Olympus SIS.""" fname = private_file('sis/4A5IE8EM_F00000409.tif') with TiffFile(fname) as tif: assert tif.is_sis assert tif.byteorder == '<' assert len(tif.pages) == 122 assert len(tif.series)...
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_sis():
"""Test read Olympus SIS.""" fname = private_file('sis/4A5IE8EM_F00000409.tif') with TiffFile(fname) as tif: assert tif.is_sis assert tif.byteorder == '<' assert len(tif.pages) == 122 assert len(tif.series) == 1 # assert page properties page = tif.pages[0] ...
) assert tuple(series.asarray()[3110, 2070, :]) == (27, 45, 59) assert series.levels[-1].shape == (195, 130, 3) assert tuple(series.asarray(level=-1)[191, 127, :]) == (30, 49, 66) assert_aszarr_method(series, level=-1) assert__str__(tif) @pytest.mark.skipif(SKIP_PRIVATE, reason=R...
110
110
367
19
91
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_sis
test_read_sis
9,277
9,309
9,277
9,278
4f5cffe13cce91f4cab9da427eb769f64f3cae1a
bigcode/the-stack
train
2315b84fa398effd57b3a28f
train
function
def test_func_stripnull(): """Test stripnull function.""" assert stripnull(b'string\x00') == b'string' assert stripnull('string\x00', null='\0') == 'string' assert ( stripnull(b'string\x00string\x00\x00', first=False) == b'string\x00string' ) assert ( stripnull('string\x0...
def test_func_stripnull():
"""Test stripnull function.""" assert stripnull(b'string\x00') == b'string' assert stripnull('string\x00', null='\0') == 'string' assert ( stripnull(b'string\x00string\x00\x00', first=False) == b'string\x00string' ) assert ( stripnull('string\x00string\x00\x00', null='\0'...
0, 43, 11, 999982) ) def test_func_natural_sorted(): """Test natural_sorted function.""" assert natural_sorted(['f1', 'f2', 'f10']) == ['f1', 'f2', 'f10'] def test_func_stripnull():
64
64
109
6
58
bioturing/tifffile
tests/test_tifffile.py
Python
test_func_stripnull
test_func_stripnull
2,557
2,568
2,557
2,557
288cd24aa9d425a98bdf1704ba492a2cdd30111b
bigcode/the-stack
train
db77c3efb62f0179ecc96ab4
train
function
@pytest.mark.skipif(SKIP_PRIVATE or SKIP_LARGE, reason=REASON) def test_read_fluoview_120816_bf_f0000(): """Test read FluoView TZYX.""" fname = private_file('fluoview/120816_bf_f0000.tif') with TiffFile(fname) as tif: assert tif.byteorder == '<' assert len(tif.pages) == 864 assert le...
@pytest.mark.skipif(SKIP_PRIVATE or SKIP_LARGE, reason=REASON) def test_read_fluoview_120816_bf_f0000():
"""Test read FluoView TZYX.""" fname = private_file('fluoview/120816_bf_f0000.tif') with TiffFile(fname) as tif: assert tif.byteorder == '<' assert len(tif.pages) == 864 assert len(tif.series) == 1 assert tif.is_fluoview # assert page properties page = tif.pag...
assert data.shape == (2, 50, 256, 256) assert data.dtype == numpy.uint16 assert round(abs(data[1, 36, 128, 128] - 824), 7) == 0 assert_aszarr_method(series, data) assert_aszarr_method(series, data, chunkmode='page') assert__str__(tif) @pytest.mark.skipif(SKIP_PRIVATE or S...
121
121
406
34
87
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_fluoview_120816_bf_f0000
test_read_fluoview_120816_bf_f0000
8,738
8,773
8,738
8,739
1ff3232681c554330f46b37380d6b030a1443f3e
bigcode/the-stack
train
81758952e34933cf1293d805
train
function
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_pilatus_100k(): """Test read Pilatus.""" fname = private_file('TvxPilatus/Pilatus100K_scan030_033.tiff') with TiffFile(fname) as tif: assert tif.byteorder == '<' assert len(tif.pages) == 1 assert tif.is_pilatus # ...
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_pilatus_100k():
"""Test read Pilatus.""" fname = private_file('TvxPilatus/Pilatus100K_scan030_033.tiff') with TiffFile(fname) as tif: assert tif.byteorder == '<' assert len(tif.pages) == 1 assert tif.is_pilatus # assert page properties page = tif.pages[0] assert page.imagewid...
(data[120, 34] - 4), 7) == 0 assert_aszarr_method(series, data) assert_aszarr_method(series, data, chunkmode='page') assert__str__(tif) @pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_pilatus_100k():
74
74
247
23
51
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_pilatus_100k
test_read_pilatus_100k
8,937
8,960
8,937
8,938
5f2e9af3d0879c3bc49d8fc3eaca044a8e8073e2
bigcode/the-stack
train
7008118f3e8c89aa2c70b646
train
function
def test_write_truncate(): """Test only one page is written for truncated files.""" shape = (4, 5, 6, 1) with TempFileName('truncate') as fname: imwrite(fname, random_data(numpy.uint8, shape), truncate=True) assert_valid_tiff(fname) with TiffFile(fname) as tif: assert len...
def test_write_truncate():
"""Test only one page is written for truncated files.""" shape = (4, 5, 6, 1) with TempFileName('truncate') as fname: imwrite(fname, random_data(numpy.uint8, shape), truncate=True) assert_valid_tiff(fname) with TiffFile(fname) as tif: assert len(tif.pages) == 1 # not 4 ...
.samplesperpixel == 1 image = page.asarray() assert_array_equal(data[i], image) # assert series series = tif.series[0] assert series.offset is not None image = series.asarray() assert_array_equal(data, image) assert_...
71
71
237
6
65
bioturing/tifffile
tests/test_tifffile.py
Python
test_write_truncate
test_write_truncate
10,206
10,227
10,206
10,206
680f527751bb4ab76aaca7b2dd44c4395edf9571
bigcode/the-stack
train
809d519105754ba38a55f3ce
train
function
@pytest.mark.parametrize('bytecount', [16, 256]) @pytest.mark.parametrize('count', [1, 2, 4]) @pytest.mark.parametrize('compression', [0, 6]) @pytest.mark.parametrize('tiled', [0, 1]) @pytest.mark.parametrize('bigtiff', [0, 1]) def test_write_bytecount(bigtiff, tiled, compression, count, bytecount): """Test write b...
@pytest.mark.parametrize('bytecount', [16, 256]) @pytest.mark.parametrize('count', [1, 2, 4]) @pytest.mark.parametrize('compression', [0, 6]) @pytest.mark.parametrize('tiled', [0, 1]) @pytest.mark.parametrize('bigtiff', [0, 1]) def test_write_bytecount(bigtiff, tiled, compression, count, bytecount):
"""Test write bytecount formats.""" if tiled: tag = 'TileByteCounts' rowsperstrip = None tile = (bytecount, bytecount) shape = { 1: (bytecount, bytecount), 2: (bytecount * 2, bytecount), 4: (bytecount * 2, bytecount * 2), }[count] e...
' else 3 # samplesperpixel = page.samplesperpixel image = tif.asarray() assert_array_equal(data, image) assert_decode_method(page) assert__str__(tif) if imagecodecs.TIFF: im = imagecodecs.imread(fname, index=None) assert_array_...
159
159
530
85
74
bioturing/tifffile
tests/test_tifffile.py
Python
test_write_bytecount
test_write_bytecount
9,766
9,826
9,766
9,771
bddf7a475a3099b70a80b74e1616f5a7f91ba52e
bigcode/the-stack
train
6e2faf279325884720b09ae6
train
function
@pytest.mark.skipif(SKIP_PUBLIC, reason=REASON) def test_issue_pages_number(): """Test number of pages.""" fname = public_file('tifffile/100000_pages.tif') with TiffFile(fname) as tif: assert len(tif.pages) == 100000 assert__str__(tif, 0)
@pytest.mark.skipif(SKIP_PUBLIC, reason=REASON) def test_issue_pages_number():
"""Test number of pages.""" fname = public_file('tifffile/100000_pages.tif') with TiffFile(fname) as tif: assert len(tif.pages) == 100000 assert__str__(tif, 0)
page() fh.seek(page.tags['StripOffsets'].valueoffset) assert ( page.dataoffsets[0] == unpack(tif.byteorder + 'I', fh.read(4))[0] ) @pytest.mark.skipif(SKIP_PUBLIC, reason=REASON) def test_issue_pages_number():
64
64
76
19
45
bioturing/tifffile
tests/test_tifffile.py
Python
test_issue_pages_number
test_issue_pages_number
817
823
817
818
1d45e71ce2b46e4f0ca69ebfee4e6e1f0c3a3329
bigcode/the-stack
train
fffed39b115ccafdef86c403
train
function
def test_write_pages(): """Test write tags for contiguous data in all pages.""" data = random_data(numpy.float32, (17, 219, 301)) with TempFileName('pages') as fname: imwrite(fname, data, photometric=MINISBLACK) assert_valid_tiff(fname) # assert file with TiffFile(fname) as t...
def test_write_pages():
"""Test write tags for contiguous data in all pages.""" data = random_data(numpy.float32, (17, 219, 301)) with TempFileName('pages') as fname: imwrite(fname, data, photometric=MINISBLACK) assert_valid_tiff(fname) # assert file with TiffFile(fname) as tif: assert l...
(public_file('tifffile/generic_series.tif')) buf = BytesIO() buf.write(pad) imwrite(buf, data, photometric=RGB) buf.write(pad) buf.seek(len(pad)) assert_array_equal(imread(buf), data) def test_write_pages():
65
65
219
5
60
bioturing/tifffile
tests/test_tifffile.py
Python
test_write_pages
test_write_pages
10,180
10,203
10,180
10,180
6110a5c3a9e2698efdbb94315b20bd2a2bd4fc03
bigcode/the-stack
train
c7e6f5acdcfa6c9c192d1e3b
train
function
@pytest.mark.skipif(SKIP_EXTENDED, reason=REASON) @pytest.mark.parametrize( 'shape', [ (219, 301), (219, 301, 2), (219, 301, 3), (219, 301, 4), (2, 219, 301), (3, 219, 301), (4, 219, 301), (5, 219, 301), (4, 3, 219, 301), (4, 219, 3...
@pytest.mark.skipif(SKIP_EXTENDED, reason=REASON) @pytest.mark.parametrize( 'shape', [ (219, 301), (219, 301, 2), (219, 301, 3), (219, 301, 4), (2, 219, 301), (3, 219, 301), (4, 219, 301), (5, 219, 301), (4, 3, 219, 301), (4, 219, 3...
"""Test TiffWriter with various options.""" # TODO: test compression ? fname = '{}_{}_{}_{}{}{}'.format( bigtiff, {'<': 'le', '>': 'be'}[byteorder], numpy.dtype(dtype).name, str(shape).replace(' ', ''), '_tiled' if tile is not None else '', '_empty' if data is...
@pytest.mark.skipif(SKIP_EXTENDED, reason=REASON) @pytest.mark.parametrize( 'shape', [ (219, 301), (219, 301, 2), (219, 301, 3), (219, 301, 4), (2, 219, 301), (3, 219, 301), (4, 219, 301), (5, 219, 301), (4, 3, 219, 301), (4, 219, 3...
248
209
698
248
0
bioturing/tifffile
tests/test_tifffile.py
Python
test_write
test_write
9,508
9,594
9,508
9,531
566d9505455a1f9ac44f3737faf1ce65ac50510d
bigcode/the-stack
train
58ed8ff13ac77c770d16ff62
train
function
@pytest.mark.skipif(SKIP_PUBLIC, reason=REASON) def test_read_ome_modulo_flim(): """Test read OME modulo FLIM.""" fname = public_file('OME/modulo/FLIM-ModuloAlongC.ome.tiff') with TiffFile(fname) as tif: assert tif.is_ome assert tif.byteorder == '>' assert len(tif.pages) == 16 ...
@pytest.mark.skipif(SKIP_PUBLIC, reason=REASON) def test_read_ome_modulo_flim():
"""Test read OME modulo FLIM.""" fname = public_file('OME/modulo/FLIM-ModuloAlongC.ome.tiff') with TiffFile(fname) as tif: assert tif.is_ome assert tif.byteorder == '>' assert len(tif.pages) == 16 assert len(tif.series) == 1 # assert page properties page = tif...
data.shape == (7, 3, 5, 167, 439) assert data.dtype == numpy.int8 assert data[6, 0, 4, 158, 428] == 91 assert_aszarr_method(tif, data) # don't squeeze data = tif.asarray(squeeze=False) assert_aszarr_method(tif, data, squeeze=False) assert__str__(tif) @pytest.mark...
119
119
399
23
96
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_ome_modulo_flim
test_read_ome_modulo_flim
7,364
7,400
7,364
7,365
367454a36e95170235e0f599c599ad88dac2a6d8
bigcode/the-stack
train
dc41c91ba6cae1fb4ccc3dfe
train
function
def test_write_short_tags(): """Test write single and sequences of words.""" data = random_data(numpy.uint8, (8, 8)) value = 65531 extratags = [ (34564, 'H', 1, (value,) * 1, False), (34565, 'H', 2, (value,) * 2, False), (34566, 'H', 3, (value,) * 3, False), (34567, 'H', ...
def test_write_short_tags():
"""Test write single and sequences of words.""" data = random_data(numpy.uint8, (8, 8)) value = 65531 extratags = [ (34564, 'H', 1, (value,) * 1, False), (34565, 'H', 2, (value,) * 2, False), (34566, 'H', 3, (value,) * 3, False), (34567, 'H', 4, (value,) * 4, False), ...
63'].value == value assert tags['34564'].value == value assert tuple(tags['34565'].value) == (value, value) assert tuple(tags['34566'].value) == (value, value) assert tuple(tags['34567'].value) == (value, value) assert__str__(tif) def test_write_short_tags():
79
79
265
6
73
bioturing/tifffile
tests/test_tifffile.py
Python
test_write_short_tags
test_write_short_tags
10,351
10,371
10,351
10,351
b475f43677fc2c42d23024f48a937ae4f938d13b
bigcode/the-stack
train
ec32101a851a58ed69161ac5
train
function
@pytest.mark.skipif(SKIP_PRIVATE or SKIP_CODECS, reason=REASON) def test_read_lena_be_f16_contig(): """Test read big endian float16 horizontal differencing.""" fname = private_file('PS/lena_be_f16_contig.tif') with TiffFile(fname) as tif: assert tif.byteorder == '>' assert len(tif.pages) == ...
@pytest.mark.skipif(SKIP_PRIVATE or SKIP_CODECS, reason=REASON) def test_read_lena_be_f16_contig():
"""Test read big endian float16 horizontal differencing.""" fname = private_file('PS/lena_be_f16_contig.tif') with TiffFile(fname) as tif: assert tif.byteorder == '>' assert len(tif.pages) == 1 assert len(tif.series) == 1 # assert page properties page = tif.pages[0] ...
spersample == 14 assert page.tags['CFARepeatPatternDim'].value == (2, 2) assert page.tags['CFAPattern'].value == b'\x00\x01\x01\x02' image = page.asarray() assert_array_equal(image, data) assert_aszarr_method(tif, data) @pytest.mark.skipif(SKIP_PRIVATE or SKIP_CODECS, reason=REAS...
101
101
337
29
72
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_lena_be_f16_contig
test_read_lena_be_f16_contig
5,179
5,210
5,179
5,180
8e6d8075831e3152587e8336a39aa5fba4db0ad9
bigcode/the-stack
train
e84b2f99576130a3177cda71
train
function
@pytest.mark.skipif(SKIP_PUBLIC, reason=REASON) def test_read_ome_multi_channel_4d_series(): """Test read OME time-series of multi-channel volumes.""" # 4D (7 time points, 5 focal planes, 3 channels) fname = public_file( 'OME/bioformats-artificial/multi-channel-4D-series.ome.tiff' ) with Tif...
@pytest.mark.skipif(SKIP_PUBLIC, reason=REASON) def test_read_ome_multi_channel_4d_series():
"""Test read OME time-series of multi-channel volumes.""" # 4D (7 time points, 5 focal planes, 3 channels) fname = public_file( 'OME/bioformats-artificial/multi-channel-4D-series.ome.tiff' ) with TiffFile(fname) as tif: assert tif.is_ome assert tif.byteorder == '>' as...
numpy.int8 assert series.axes == 'TZYX' assert not series.is_multifile # assert data data = tif.asarray() assert isinstance(data, numpy.ndarray) assert data.shape == (7, 5, 167, 439) assert data.dtype == numpy.int8 assert data[6, 4, 158, 428] == 91 ...
130
130
436
25
105
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_ome_multi_channel_4d_series
test_read_ome_multi_channel_4d_series
7,322
7,361
7,322
7,323
c8f8135c3bdfb133e4712f5508295638a1f14d4c
bigcode/the-stack
train
a874215809ffc2d89363fd0b
train
function
def test_write_extrasamples_gray_mix(): """Test write grayscale with multiple extrasamples.""" data = random_data(numpy.uint8, (301, 219, 4)) with TempFileName('extrasamples_gray_mix') as fname: imwrite( fname, data, photometric=MINISBLACK, extrasample...
def test_write_extrasamples_gray_mix():
"""Test write grayscale with multiple extrasamples.""" data = random_data(numpy.uint8, (301, 219, 4)) with TempFileName('extrasamples_gray_mix') as fname: imwrite( fname, data, photometric=MINISBLACK, extrasamples=[ASSOCALPHA, UNASSALPHA, UNSPECIFIED],...
assert page.samplesperpixel == 2 assert page.extrasamples[0] == 2 image = tif.asarray() assert_array_equal(data, image) assert_aszarr_method(tif, image) assert__str__(tif) def test_write_extrasamples_gray_mix():
66
66
221
9
57
bioturing/tifffile
tests/test_tifffile.py
Python
test_write_extrasamples_gray_mix
test_write_extrasamples_gray_mix
11,406
11,429
11,406
11,406
c7eb9c68bdc2ccecc644d782062ed5d3473e8c67
bigcode/the-stack
train
13b44ade87fe98fe9387740e
train
function
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_stk_greenbeads(): """Test read MetaMorph STK time-series, but time_created is corrupt (?).""" # 8bit palette is present but should not be applied fname = private_file('stk/greenbeads.stk') with TiffFile(fname) as tif: assert tif.is_s...
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_stk_greenbeads():
"""Test read MetaMorph STK time-series, but time_created is corrupt (?).""" # 8bit palette is present but should not be applied fname = private_file('stk/greenbeads.stk') with TiffFile(fname) as tif: assert tif.is_stk assert tif.byteorder == '<' assert len(tif.pages) == 1 ...
assert series properties series = tif.series[0] assert series.shape == (10, 191, 196) assert series.dtype == numpy.uint8 assert series.axes == 'ZYX' # assert data data = tif.asarray() assert isinstance(data, numpy.ndarray) assert data.shape == (10, 191, 1...
149
149
497
22
127
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_stk_greenbeads
test_read_stk_greenbeads
6,361
6,405
6,361
6,362
894ac04de80000fca210ed3749fdbab051cb6ba0
bigcode/the-stack
train
80abb51aa9c4f6727b50b3e7
train
function
@pytest.mark.parametrize('samples', [1, 3]) def test_issue_tiles_pad(samples): """Test tiles from iterator get padded.""" # https://github.com/cgohlke/tifffile/issues/38 if samples == 3: data = numpy.random.randint(0, 2**12, (31, 33, 3), numpy.uint16) photometric = 'rgb' else: da...
@pytest.mark.parametrize('samples', [1, 3]) def test_issue_tiles_pad(samples):
"""Test tiles from iterator get padded.""" # https://github.com/cgohlke/tifffile/issues/38 if samples == 3: data = numpy.random.randint(0, 2**12, (31, 33, 3), numpy.uint16) photometric = 'rgb' else: data = numpy.random.randint(0, 2**12, (31, 33), numpy.uint16) photometric...
assert page.is_memmappable assert page.is_tiled assert ( page.tags['TileOffsets'].value[0] + page.tags['TileByteCounts'].value[0] == tif.filehandle.size ) assert_array_equal(page.asarray(), data) asse...
97
97
325
19
78
bioturing/tifffile
tests/test_tifffile.py
Python
test_issue_tiles_pad
test_issue_tiles_pad
939
974
939
940
4e390a03e168a98e7c4ecd67b9dec9fb1756139f
bigcode/the-stack
train
d739d4fa9154dbca8f9d418a
train
function
@pytest.mark.skipif(SKIP_PUBLIC or SKIP_CODECS, reason=REASON) def test_write_roundtrip_filename(): """Test write and read using file name.""" data = imread(public_file('tifffile/generic_series.tif')) with TempFileName('roundtrip_filename') as fname: imwrite(fname, data, photometric=RGB) ass...
@pytest.mark.skipif(SKIP_PUBLIC or SKIP_CODECS, reason=REASON) def test_write_roundtrip_filename():
"""Test write and read using file name.""" data = imread(public_file('tifffile/generic_series.tif')) with TempFileName('roundtrip_filename') as fname: imwrite(fname, data, photometric=RGB) assert_array_equal(imread(fname), data)
.imagewidth == 31 assert page.imagelength == 21 assert_array_equal(tif.asarray(series=1)[1], data) assert__str__(tif) @pytest.mark.skipif(SKIP_PUBLIC or SKIP_CODECS, reason=REASON) def test_write_roundtrip_filename():
64
64
88
25
39
bioturing/tifffile
tests/test_tifffile.py
Python
test_write_roundtrip_filename
test_write_roundtrip_filename
10,143
10,149
10,143
10,144
b7c6981140c4afca4bdd5d9ded221998b1f6dfde
bigcode/the-stack
train
ffcf8db61c0bc9909d664617
train
function
@pytest.mark.skipif(SKIP_CODECS or not imagecodecs.WEBP, reason=REASON) def test_write_compression_webp(): """Test write WEBP compression.""" data = WRITE_DATA.astype(numpy.uint8).reshape((219, 301, 3)) with TempFileName('compression_webp') as fname: imwrite(fname, data, compression=(WEBP, -1), phot...
@pytest.mark.skipif(SKIP_CODECS or not imagecodecs.WEBP, reason=REASON) def test_write_compression_webp():
"""Test write WEBP compression.""" data = WRITE_DATA.astype(numpy.uint8).reshape((219, 301, 3)) with TempFileName('compression_webp') as fname: imwrite(fname, data, compression=(WEBP, -1), photometric=RGB) assert_valid_tiff(fname) with TiffFile(fname) as tif: assert len(t...
image = tif.asarray() assert_array_equal(data, image) assert_aszarr_method(tif, image) assert__str__(tif) @pytest.mark.skipif(SKIP_CODECS or not imagecodecs.WEBP, reason=REASON) def test_write_compression_webp():
64
64
215
30
34
bioturing/tifffile
tests/test_tifffile.py
Python
test_write_compression_webp
test_write_compression_webp
10,876
10,895
10,876
10,877
e97ce5809a1244a91e68743643fb6d53d3740392
bigcode/the-stack
train
6767b9f3adaec5d9a8b81336
train
function
def test_func_pformat_printable_unicode(): """Test pformat function with printable unicode.""" value = ( '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST' 'UVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' ) assert pformat(value, height=1, width=60) == ( '0123456...
def test_func_pformat_printable_unicode():
"""Test pformat function with printable unicode.""" value = ( '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST' 'UVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' ) assert pformat(value, height=1, width=60) == ( '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN...
, height=8, width=60) == r""" 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX """.strip() ) # YZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ def test_func_pformat_printable_unicode():
63
64
137
9
54
bioturing/tifffile
tests/test_tifffile.py
Python
test_func_pformat_printable_unicode
test_func_pformat_printable_unicode
3,013
3,029
3,013
3,013
baf3656970af89cd50b19c92994ad5a78fad2aa7
bigcode/the-stack
train
1b764daa0b9652c5d9677356
train
function
def test_func_julian_datetime(): """Test julian_datetime function.""" assert julian_datetime(2451576, 54362783) == ( datetime.datetime(2000, 2, 2, 15, 6, 2, 783) )
def test_func_julian_datetime():
"""Test julian_datetime function.""" assert julian_datetime(2451576, 54362783) == ( datetime.datetime(2000, 2, 2, 15, 6, 2, 783) )
(3, 4, 219, 2, 301, 1)) with pytest.raises(ValueError): reshape_axes('IYX', (12, 219, 301), (3, 4, 219, 301, 2)) def test_func_julian_datetime():
64
64
60
8
56
bioturing/tifffile
tests/test_tifffile.py
Python
test_func_julian_datetime
test_func_julian_datetime
2,538
2,542
2,538
2,538
b76933220f6c62c2eb9a83230e8a8b1625a957b5
bigcode/the-stack
train
ec862a0e9e6917c96378bec0
train
function
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_imagej_invalid_metadata(caplog): """Test read bad ImageJ metadata.""" # file contains 1 page but metadata claims 3500 images # memory map big endian data fname = private_file('sima/0.tif') with TiffFile(fname) as tif: assert tif....
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_imagej_invalid_metadata(caplog):
"""Test read bad ImageJ metadata.""" # file contains 1 page but metadata claims 3500 images # memory map big endian data fname = private_file('sima/0.tif') with TiffFile(fname) as tif: assert tif.is_imagej assert tif.byteorder == '>' assert len(tif.pages) == 1 assert ...
assert isinstance(data, numpy.core.memmap) assert data.shape == (100000, 64, 64) assert data.dtype == numpy.dtype('>u2') assert round(abs(data[7310, 25, 25] - 100), 7) == 0 # too slow: assert_aszarr_method(series, data) assert__str__(tif, 0) del data @pytest.mark....
115
115
385
23
91
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_imagej_invalid_metadata
test_read_imagej_invalid_metadata
8,623
8,661
8,623
8,624
1eaed012536a17e59f2a8be6937713a33d492f64
bigcode/the-stack
train
feef04fb69c97d3cfc1e0463
train
function
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_lsm_take1(): """Test read LSM: TCZYX (Plane mode), single image, uint8.""" fname = private_file('lsm/take1.lsm') with TiffFile(fname) as tif: assert tif.is_lsm assert tif.byteorder == '<' assert len(tif.pages) == 2 ...
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_lsm_take1():
"""Test read LSM: TCZYX (Plane mode), single image, uint8.""" fname = private_file('lsm/take1.lsm') with TiffFile(fname) as tif: assert tif.is_lsm assert tif.byteorder == '<' assert len(tif.pages) == 2 assert len(tif.series) == 2 # assert page properties page ...
series.dtype == numpy.uint8 assert series.shape == (36000, 3, 40, 128) assert series.axes == 'TSYX' assert series.get_shape(False) == (1, 1, 36000, 3, 40, 128) assert series.get_axes(False) == 'ZCTSYX' # assert lsm_info tags tags = tif.lsm_metadata ...
232
232
775
21
211
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_lsm_take1
test_read_lsm_take1
5,882
5,955
5,882
5,883
67d709c7f45868beb362ad6e6e40ad0df8af752b
bigcode/the-stack
train
f2638908688a3ed08e07339b
train
function
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_sem_bad_metadata(): """Test read Zeiss SEM metadata with wrong length.""" # reported by Klaus Schwarzburg on 8/27/2018 fname = private_file('issues/sem_bad_metadata.tif') with TiffFile(fname) as tif: assert tif.is_sem assert ...
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_sem_bad_metadata():
"""Test read Zeiss SEM metadata with wrong length.""" # reported by Klaus Schwarzburg on 8/27/2018 fname = private_file('issues/sem_bad_metadata.tif') with TiffFile(fname) as tif: assert tif.is_sem assert tif.byteorder == '<' assert len(tif.pages) == 1 assert len(tif.seri...
'1024 * 768') assert sem['ap_fib_fg_emission_actual'] == ( 'Flood Gun Emission Actual', 0.0, 'µA', ) assert_aszarr_method(tif) assert__str__(tif) @pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_read_sem_bad_metadata():
79
79
266
20
59
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_sem_bad_metadata
test_read_sem_bad_metadata
9,369
9,393
9,369
9,370
becb551f779ea179043965f2cc23d9b27d496bc2
bigcode/the-stack
train
2171149f77504f052f966dc9
train
function
def test_write_extrasamples_mix(): """Test write RGB with mixture of extrasamples.""" data = random_data(numpy.uint8, (219, 301, 6)) with TempFileName('extrasamples_mix') as fname: imwrite( fname, data, photometric=RGB, extrasamples=[ASSOCALPHA, UNASSA...
def test_write_extrasamples_mix():
"""Test write RGB with mixture of extrasamples.""" data = random_data(numpy.uint8, (219, 301, 6)) with TempFileName('extrasamples_mix') as fname: imwrite( fname, data, photometric=RGB, extrasamples=[ASSOCALPHA, UNASSALPHA, UNSPECIFIED], ) ...
assert page.samplesperpixel == 4 assert page.extrasamples[0] == 1 image = tif.asarray() assert_array_equal(data, image) assert_aszarr_method(tif, image) assert__str__(tif) def test_write_extrasamples_mix():
64
64
216
8
56
bioturing/tifffile
tests/test_tifffile.py
Python
test_write_extrasamples_mix
test_write_extrasamples_mix
11,474
11,497
11,474
11,474
489cb5254739e01f98d0b4bcb0c6e03ed2773787
bigcode/the-stack
train
48b761c0ff384034ae66a4b4
train
function
@pytest.mark.skipif(SKIP_ZARR or SKIP_DASK, reason=REASON) @pytest.mark.parametrize('truncate', [False, True]) @pytest.mark.parametrize('chunkmode', [0, 2]) def test_issue_dask_multipage(truncate, chunkmode): """Test multi-threaded access of memory-mapable, multi-page Zarr stores.""" # https://github.com/cgohlk...
@pytest.mark.skipif(SKIP_ZARR or SKIP_DASK, reason=REASON) @pytest.mark.parametrize('truncate', [False, True]) @pytest.mark.parametrize('chunkmode', [0, 2]) def test_issue_dask_multipage(truncate, chunkmode):
"""Test multi-threaded access of memory-mapable, multi-page Zarr stores.""" # https://github.com/cgohlke/tifffile/issues/67#issuecomment-908529425 import dask.array data = numpy.arange(5 * 99 * 101, dtype=numpy.uint16).reshape((5, 99, 101)) with TempFileName( f'test_issue_dask_multipage_{in...
data = tif.asarray() assert_aszarr_method(tif, data) @pytest.mark.skipif(SKIP_ZARR or SKIP_DASK, reason=REASON) @pytest.mark.parametrize('truncate', [False, True]) @pytest.mark.parametrize('chunkmode', [0, 2]) def test_issue_dask_multipage(truncate, chunkmode):
74
74
248
57
17
bioturing/tifffile
tests/test_tifffile.py
Python
test_issue_dask_multipage
test_issue_dask_multipage
1,471
1,489
1,471
1,474
1ad9461cec9aa4a013b236ed869522b125fab6cb
bigcode/the-stack
train
9dd37361befde989b5c1e638
train
function
@pytest.mark.skipif( SKIP_PUBLIC or SKIP_CODECS or not imagecodecs.ZSTD, reason=REASON ) def test_read_zstd(): """Test read ZStd compression.""" fname = public_file('GDAL/byte_zstd.tif') with TiffFile(fname) as tif: assert len(tif.pages) == 1 page = tif.pages[0] assert page.compr...
@pytest.mark.skipif( SKIP_PUBLIC or SKIP_CODECS or not imagecodecs.ZSTD, reason=REASON ) def test_read_zstd():
"""Test read ZStd compression.""" fname = public_file('GDAL/byte_zstd.tif') with TiffFile(fname) as tif: assert len(tif.pages) == 1 page = tif.pages[0] assert page.compression == ZSTD assert page.photometric == MINISBLACK assert page.planarconfig == CONTIG ass...
(image[25, 25]) == (3265, 1558, 2811) assert_aszarr_method(tif, image) assert__str__(tif) @pytest.mark.skipif( SKIP_PUBLIC or SKIP_CODECS or not imagecodecs.ZSTD, reason=REASON ) def test_read_zstd():
73
73
244
34
39
bioturing/tifffile
tests/test_tifffile.py
Python
test_read_zstd
test_read_zstd
5,089
5,112
5,089
5,092
7166f35922e4bc011bf8ef4fd1dcee396cfb1953
bigcode/the-stack
train
d75a598b019542a02da5f587
train
function
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_depend_roifile(): """Test roifile.ImagejRoi class.""" from roifile import ImagejRoi # noqa for roi in ImagejRoi.fromfile(private_file('imagej/IJMetadata.tif')): assert roi == ImagejRoi.frombytes(roi.tobytes()) roi.coordinates() ...
@pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_depend_roifile():
"""Test roifile.ImagejRoi class.""" from roifile import ImagejRoi # noqa for roi in ImagejRoi.fromfile(private_file('imagej/IJMetadata.tif')): assert roi == ImagejRoi.frombytes(roi.tobytes()) roi.coordinates() roi.__str__()
s.aszarr(codec=imagecodecs.png_decode) as store: assert_array_equal(data, zarr.open(store, mode='r')) del data ############################################################################### # Test packages depending on tifffile @pytest.mark.skipif(SKIP_PRIVATE, reason=REASON) def test_depend_roifile...
64
64
92
20
43
bioturing/tifffile
tests/test_tifffile.py
Python
test_depend_roifile
test_depend_roifile
14,221
14,229
14,221
14,222
d861375d6fc7708608ff6dfae53efe81eee33338
bigcode/the-stack
train
7c9d4eb0ec506ac7daf88d41
train
function
@pytest.mark.parametrize( 'args', [(0, 0), (1, 5), (2, ADOBE_DEFLATE), (3, ADOBE_DEFLATE, 5)] ) def test_write_compress_args(args): """Test deprecated compress parameter.""" i = args[0] compressargs = args[1:] compressed = compressargs[0] != 0 if len(compressargs) == 1: compressargs = co...
@pytest.mark.parametrize( 'args', [(0, 0), (1, 5), (2, ADOBE_DEFLATE), (3, ADOBE_DEFLATE, 5)] ) def test_write_compress_args(args):
"""Test deprecated compress parameter.""" i = args[0] compressargs = args[1:] compressed = compressargs[0] != 0 if len(compressargs) == 1: compressargs = compressargs[0] data = WRITE_DATA with TempFileName(f'compression_args_{i}') as fname: with pytest.warns(DeprecationWarni...
(page.dataoffsets) == (9 if compressed else 3) image = tif.asarray() assert_array_equal(data, image) assert__str__(tif) @pytest.mark.parametrize( 'args', [(0, 0), (1, 5), (2, ADOBE_DEFLATE), (3, ADOBE_DEFLATE, 5)] ) def test_write_compress_args(args):
88
88
296
52
36
bioturing/tifffile
tests/test_tifffile.py
Python
test_write_compress_args
test_write_compress_args
10,680
10,708
10,680
10,683
3233dff107ac90c4e57180fc7049c3e17f6277c5
bigcode/the-stack
train
8a958fbff1a4c7fe47d948e5
train
function
@passport_blu.route('/sms_code', methods=['POST']) def send_sms_code(): """ 发送短信的逻辑 1. 获取参数:手机号,图片验证码内容,图片验证码的编号 (随机值) 2. 校验参数(参数是否符合规则,判断是否有值) 3. 先从redis中取出真实的验证码内容 4. 与用户的验证码内容进行对比,如果对比不一致,那么返回验证码输入错误 5. 如果一致,生成验证码的内容(随机数据) 6. 发送短信验证码,并保存验证码,以便校验 7. 告知发送结果 """ # 本质:最后调用load...
@passport_blu.route('/sms_code', methods=['POST']) def send_sms_code():
""" 发送短信的逻辑 1. 获取参数:手机号,图片验证码内容,图片验证码的编号 (随机值) 2. 校验参数(参数是否符合规则,判断是否有值) 3. 先从redis中取出真实的验证码内容 4. 与用户的验证码内容进行对比,如果对比不一致,那么返回验证码输入错误 5. 如果一致,生成验证码的内容(随机数据) 6. 发送短信验证码,并保存验证码,以便校验 7. 告知发送结果 """ # 本质:最后调用loads函数 parameters = flask.request.json # parameters = flask.json.lo...
的值 image_code_id = flask.request.args.get('imageCodeId', None) if not image_code_id: flask.abort(403) # 生成图片验证码,图片内容需要保存 name, text, image = captcha.generate_captcha() # 数据库操作都需要在try中实现 try: redis_db.set('imageCodeId' + image_code_id, text, constants.IMAGE_CODE_REDIS_EXPIRES) ...
183
183
612
18
164
Wingxy/Python_Study
02-flask_project/info/modules/passport/views.py
Python
send_sms_code
send_sms_code
48
99
48
49
984008d1b29af40a59ff44c7eb98eba02079eb7d
bigcode/the-stack
train
b5f6f9ca6dec5494a268efa0
train
function
@passport_blu.route('/register', methods=['POST']) def register(): """ 注册的逻辑 1. 获取参数 2. 校验参数 3. 取到服务器保存的真实的短信验证码内容 4. 校验用户输入的短信验证码内容和真实验证码内容是否一致 5. 如果一致,初始化 User 模型,并且赋值属性 6. 将 user 模型添加数据库 7. 返回响应 """ parameters = flask.request.json mobile_phone = parameters.get('mobile'...
@passport_blu.route('/register', methods=['POST']) def register():
""" 注册的逻辑 1. 获取参数 2. 校验参数 3. 取到服务器保存的真实的短信验证码内容 4. 校验用户输入的短信验证码内容和真实验证码内容是否一致 5. 如果一致,初始化 User 模型,并且赋值属性 6. 将 user 模型添加数据库 7. 返回响应 """ parameters = flask.request.json mobile_phone = parameters.get('mobile') sms_code = parameters.get('smscode') password = parameter...
_code_str, constants.SMS_CODE_REDIS_EXPIRES / 5], '1') if result != 0: return flask.jsonify(errno=RET.THIRDERR, errmsg='发送短信失败') else: try: # 手机号作为key redis_db.set(mobile_phone, sms_code_str, constants.SMS_CODE_REDIS_EXPIRES) except Ex...
141
141
473
15
126
Wingxy/Python_Study
02-flask_project/info/modules/passport/views.py
Python
register
register
102
154
102
103
14bdf694e30750596eba6191c95d10c10cc7f432
bigcode/the-stack
train
53e283a259facde79b6cca5a
train
function
@passport_blu.route('/image_code') def get_image_code(): """ 生成图片验证码并返回 1. 取到参数 2. 判断参数是否有值 3. 生成图片验证码 4. 保存图片验证码文字内容到redis 5. 返回验证码图片 """ # 请求参数可以通过.com/image_code?imageCodeId=xxxxx 发送 # 通过request.args()获取参数的内容,每次只能取一个key对应的值 image_code_id = flask.request.args.get('imageCode...
@passport_blu.route('/image_code') def get_image_code():
""" 生成图片验证码并返回 1. 取到参数 2. 判断参数是否有值 3. 生成图片验证码 4. 保存图片验证码文字内容到redis 5. 返回验证码图片 """ # 请求参数可以通过.com/image_code?imageCodeId=xxxxx 发送 # 通过request.args()获取参数的内容,每次只能取一个key对应的值 image_code_id = flask.request.args.get('imageCodeId', None) if not image_code_id: flask.abort...
random import re import datetime import flask from info import redis_db, db from info.models import User from info.utils import constants from info.utils.captcha.captcha import captcha from info.utils.response_code import RET from info.libs.yuntongxun.sms import CCP from . import passport_blu @passport_blu.route('/i...
82
82
275
14
67
Wingxy/Python_Study
02-flask_project/info/modules/passport/views.py
Python
get_image_code
get_image_code
16
45
16
17
689494aa7aa263f1bdb700e7bcd0564e4ebb2944
bigcode/the-stack
train
f17bd0fc4ae6ae667b5e1c01
train
function
@passport_blu.route('/logout') def logout(): flask.session.pop('user_id', None) flask.session.pop('mobile', None) flask.session.pop('nick_name', None) # 退出时一定要清楚is_admin的session值 flask.session.pop('is_admin', None) return flask.jsonify(errno=RET.OK, errmsg='退出成功')
@passport_blu.route('/logout') def logout():
flask.session.pop('user_id', None) flask.session.pop('mobile', None) flask.session.pop('nick_name', None) # 退出时一定要清楚is_admin的session值 flask.session.pop('is_admin', None) return flask.jsonify(errno=RET.OK, errmsg='退出成功')
相关配置 # try: # db.session.commit() # except Exception as e: # db.session.rollback() # flask.current_app.logger.error(e) return flask.jsonify(errno=RET.OK, errmsg='登录成功') @passport_blu.route('/logout') def logout():
64
64
80
11
53
Wingxy/Python_Study
02-flask_project/info/modules/passport/views.py
Python
logout
logout
196
204
196
197
882090b2f348ba1a51989b39d12ec153544ae791
bigcode/the-stack
train
109942a2f9669b1e4c0072c2
train
function
@passport_blu.route('/login', methods=['POST']) def login(): parameters = flask.request.json mobile = parameters.get('mobile', None) password = parameters.get('password', None) if not all([mobile, password]): return flask.jsonify(errno=RET.PARAMERR, errmsg='参数错误') if not re.match('1[35678]\...
@passport_blu.route('/login', methods=['POST']) def login():
parameters = flask.request.json mobile = parameters.get('mobile', None) password = parameters.get('password', None) if not all([mobile, password]): return flask.jsonify(errno=RET.PARAMERR, errmsg='参数错误') if not re.match('1[35678]\\d{9}', mobile): return flask.jsonify(errno=RET.PARAM...
(user) db.session.commit() except Exception as e: db.session.rollback() flask.current_app.logger.error(e) return flask.jsonify(errno=RET.DBERR, errmsg='数据库保存失败') else: flask.session['user_id'] = user.id flask.session['mobile'] = use...
109
109
364
15
94
Wingxy/Python_Study
02-flask_project/info/modules/passport/views.py
Python
login
login
157
193
157
158
66326d4831bb6b2d77651e269d37f90a566ab61f
bigcode/the-stack
train
93fd009e18f5dc9910aabb02
train
class
class Migration(migrations.Migration): dependencies = [ ("core", "0048_auto_20180802_1248"), ("core", "0047_merge_20180801_1859"), ] operations = []
class Migration(migrations.Migration):
dependencies = [ ("core", "0048_auto_20180802_1248"), ("core", "0047_merge_20180801_1859"), ] operations = []
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2018-08-07 13:52 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration):
52
64
49
7
44
RTIInternational/SMART
backend/django/core/migrations/0049_merge_20180807_1352.py
Python
Migration
Migration
8
15
8
9
00402de1fe1c5df385f939ccb067eb41f4e2bc23
bigcode/the-stack
train
a1fe57cf66e2ccc553d49148
train
class
class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='InternalAccount', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ...
class Migration(migrations.Migration):
initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='InternalAccount', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('amount', models.IntegerField...
# Generated by Django 3.2 on 2021-04-18 12:20 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
43
64
183
7
35
Tm2197/Python-Architecture-Patterns
chapter_04_data_layer/account_example/account_example/example/migrations/0001_initial.py
Python
Migration
Migration
7
31
7
8
5b4be74e3d5c3460009c455e2b22998ad29fea55
bigcode/the-stack
train
43f17c416c58c3943b05188b
train
class
class AuthTokenSerializer(serializers.Serializer): '''Serializer for the user authentication object''' email = serializers.CharField() password = serializers.CharField( style={'input_type': 'password'}, trim_whitespace=False ) def validate(self, attrs): '''Validate and authe...
class AuthTokenSerializer(serializers.Serializer):
'''Serializer for the user authentication object''' email = serializers.CharField() password = serializers.CharField( style={'input_type': 'password'}, trim_whitespace=False ) def validate(self, attrs): '''Validate and authenticate the user''' email = attrs.get('emai...
validated_data): '''Update a user, setting the password correctly and return it''' password = validated_data.pop('password', None) user = super().update(instance, validated_data) if password: user.set_password(password) user.save() return user class Aut...
64
64
140
7
56
howard5248/django-restAPI-1
app/user/serializers.py
Python
AuthTokenSerializer
AuthTokenSerializer
31
54
31
31
ac8c3cfba4bd05d16669acf560f923bad721c413
bigcode/the-stack
train
1740cec7d33b2bb097fb46da
train
class
class UserSerializer(serializers.ModelSerializer): '''Serializer for the users object''' class Meta: model = get_user_model() fields = ('email', 'password', 'name') extra_kwargs = {'password': {'write_only': True, 'min_length': 5}} def create(self, validated_data): '''creat...
class UserSerializer(serializers.ModelSerializer):
'''Serializer for the users object''' class Meta: model = get_user_model() fields = ('email', 'password', 'name') extra_kwargs = {'password': {'write_only': True, 'min_length': 5}} def create(self, validated_data): '''create a new user with encrypted password and return it'...
from django.contrib.auth import get_user_model, authenticate from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class UserSerializer(serializers.ModelSerializer):
35
64
156
7
27
howard5248/django-restAPI-1
app/user/serializers.py
Python
UserSerializer
UserSerializer
7
28
7
7
6f4fccc7a91bc34028f613b72b97172156272b74
bigcode/the-stack
train
7466d5df8c4cb1a46c1d7e1d
train
class
class Migration(migrations.Migration): dependencies = [ ('analysislog', '0002_auto_20210717_1810'), ] operations = [ migrations.AlterField( model_name='analysislog', name='success', field=models.CharField(max_length=255, null=True, verbose_name='成功'), ...
class Migration(migrations.Migration):
dependencies = [ ('analysislog', '0002_auto_20210717_1810'), ] operations = [ migrations.AlterField( model_name='analysislog', name='success', field=models.CharField(max_length=255, null=True, verbose_name='成功'), ), ]
# Generated by Django 3.2.5 on 2021-07-17 09:38 from django.db import migrations, models class Migration(migrations.Migration):
38
64
73
7
30
amatsukixgithub/django_practice
analysislog/migrations/0003_alter_analysislog_success.py
Python
Migration
Migration
6
18
6
7
148ac4b7e4ce978bddd92008e963474b12be9871
bigcode/the-stack
train
0225a5dbc460e0d437a98aa5
train
function
@app.callback( Output('scatter-lr', 'figure'), [Input('biomolecule_id-lr', 'value'), Input('group-checklist-lr','value'), Input('clinical_measurement-lr', 'value')]) def update_biomolecule_scatter(biomolecule_id, groups, clinical_measurement): biomolecule_name = global_names_dict["combined"][biomol...
@app.callback( Output('scatter-lr', 'figure'), [Input('biomolecule_id-lr', 'value'), Input('group-checklist-lr','value'), Input('clinical_measurement-lr', 'value')]) def update_biomolecule_scatter(biomolecule_id, groups, clinical_measurement):
biomolecule_name = global_names_dict["combined"][biomolecule_id] fig = correlation_scatter(combined_omics_df, biomolecule_id, groups, biomolecule_name, clinical_measurement) return fig
@app.callback( Output('scatter-lr', 'figure'), [Input('biomolecule_id-lr', 'value'), Input('group-checklist-lr','value'), Input('clinical_measurement-lr', 'value')]) def update_biomolecule_scatter(biomolecule_id, groups, clinical_measurement):
69
64
116
69
0
ijmiller2/COVID-19_Multi-Omics
src/dash/apps/linear_regression.py
Python
update_biomolecule_scatter
update_biomolecule_scatter
196
207
196
202
3f7f25fab353a558680630058ce04c1d4a28ab03
bigcode/the-stack
train
692a610d73e3d6a94191f578
train
function
def blankScreen(disp, pix): ### pylint: disable=unused-argument """A blank screen used to hide any serial console output.""" if disp is None: return disp.show(Group(max_size=1))
def blankScreen(disp, pix): ### pylint: disable=unused-argument
"""A blank screen used to hide any serial console output.""" if disp is None: return disp.show(Group(max_size=1))
CHOICE_COL = (0x040000, ### Red for Rock 0x030004, ### Purple for Paper 0x000004 ### Sapphire blue for Scissors ) def blankScreen(disp, pix): ### pylint: disable=unused-argument
64
64
49
18
46
dglaude/circuitpython-examples
clue/rps_display.py
Python
blankScreen
blankScreen
75
81
75
76
f0d8946879912db55cad58e2b0f65b8a8bcab59a
bigcode/the-stack
train
660674f58a526e9cd021213a
train
class
class RPSDisplay(): def __init__(self, disp, pix, choices, sample, sample_victory, max_players, button_y_pos, sprite_filename, sprite_transparent=0, ble_color=0x000010): self.disp = disp self.std_brightness = self...
class RPSDisplay():
def __init__(self, disp, pix, choices, sample, sample_victory, max_players, button_y_pos, sprite_filename, sprite_transparent=0, ble_color=0x000010): self.disp = disp self.std_brightness = self.disp.brightness if d...
= 0xff0000 ORANGE_COL = 0xff8000 YELLOW_COL = 0xffff00 DRAWLOSE_COL = 0x0000f0 ### NeoPixel colours GAMENO_GREEN = 0x001200 ROUNDNO_WHITE = 0x0181818 PLAYER_COL = 0xff0000 SCORE_COLS = (0x200600, 0x201300, 0x001200, 0x000020, 0x08000e, 0x140618) ### Colours for NeoPixels on display-less CPB ### Should be dim to avoi...
256
256
6,768
5
251
dglaude/circuitpython-examples
clue/rps_display.py
Python
RPSDisplay
RPSDisplay
84
833
84
85
faa913fc864aca9d1b6925a25e0463cb1a2f4bb3
bigcode/the-stack
train
d2832c346d93647897080205
train
class
class TestStringMethods(unittest.TestCase): def test_get_message_pass(self): client_id = "message_pass" kube_add = "localhost:50000" queue=MessageQueue("Get_Messages{}".format(randomString(10)), client_id, kube_add) mm = [] message = create_queue_message("first ...
class TestStringMethods(unittest.TestCase):
def test_get_message_pass(self): client_id = "message_pass" kube_add = "localhost:50000" queue=MessageQueue("Get_Messages{}".format(randomString(10)), client_id, kube_add) mm = [] message = create_queue_message("first test Ack", "hi there".encode('UTF-8')) ...
import unittest, random, string from kubemq.queue.message_queue import MessageQueue from kubemq.queue.message import Message from kubemq.grpc import QueueMessagePolicy import time import datetime def create_queue_message(meta_data, body, policy=None): message = Message() message.metadata = meta_data messa...
118
256
1,097
9
108
sergejkozin-qs/kubemq-Python
examples/unit_test/queue_transaction_tests.py
Python
TestStringMethods
TestStringMethods
21
164
21
24
310b9d3a09fdbbab563ba64dbbef01fbf852c034
bigcode/the-stack
train
bb001631d66de8670fd5d6ec
train
function
def randomString(stringLength=10): """Generate a random string of fixed length """ letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(stringLength))
def randomString(stringLength=10):
"""Generate a random string of fixed length """ letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(stringLength))
tr=queue.create_transaction() recm=tr.receive(5) tr.ack_message(recm.message.Attributes.Sequence) time.sleep(0.1) recMod=tr.extend_visibility(5) self.assertTrue(recMod.is_error) def randomString(stringLength=10):
62
64
43
8
54
sergejkozin-qs/kubemq-Python
examples/unit_test/queue_transaction_tests.py
Python
randomString
randomString
171
174
171
171
1eb5a64322ce5074a9e85c8b3e2074f1b31aafc5
bigcode/the-stack
train
bbcd6a00b253c00ea9a993b7
train
function
def create_queue_message(meta_data, body, policy=None): message = Message() message.metadata = meta_data message.body = body message.tags = [ ('key', 'value'), ('key2', 'value2'), ] message.attributes = None message.policy = policy return message
def create_queue_message(meta_data, body, policy=None):
message = Message() message.metadata = meta_data message.body = body message.tags = [ ('key', 'value'), ('key2', 'value2'), ] message.attributes = None message.policy = policy return message
import unittest, random, string from kubemq.queue.message_queue import MessageQueue from kubemq.queue.message import Message from kubemq.grpc import QueueMessagePolicy import time import datetime def create_queue_message(meta_data, body, policy=None):
52
64
69
12
39
sergejkozin-qs/kubemq-Python
examples/unit_test/queue_transaction_tests.py
Python
create_queue_message
create_queue_message
9
19
9
9
c8afc8a48bcd39a7bf78c912e107c73c0eaea073
bigcode/the-stack
train
8ed9914a425f7fa2aa599958
train
class
class TestMySLRModel(AsyncTestCase): @classmethod def setUpClass(cls): # Create a temporary directory to store the trained model cls.model_dir = tempfile.TemporaryDirectory() # Create an instance of the model cls.model = MySLRModel( feature=Feature("X", float, 1), ...
class TestMySLRModel(AsyncTestCase): @classmethod
def setUpClass(cls): # Create a temporary directory to store the trained model cls.model_dir = tempfile.TemporaryDirectory() # Create an instance of the model cls.model = MySLRModel( feature=Feature("X", float, 1), predict=Feature("Y", float, 1), d...
[15.5, 14.0], [16.7, 14.6], ] TEST_DATA = [ [17.3, 15.1], [18.4, 16.1], [19.2, 16.8], [17.4, 15.2], [19.5, 17.0], [19.7, 17.2], [21.2, 18.6], ] class TestMySLRModel(AsyncTestCase): @classmethod
119
119
397
15
104
SGeetansh/dffml
dffml/skel/model/tests/test_model.py
Python
TestMySLRModel
TestMySLRModel
37
78
37
38
475ff5dcd9da42482ae1acccae2f904bdd9327c6
bigcode/the-stack
train
8cdd549eced8d12b9b001b4d
train
class
class ManagedGstreamer(ManagedApplication): """ Instance corresponds to a gstreamer application managed entity. """ def __init__(self, url, slug, window, respawn=True, extra_args=''): self.window = window self.url = url self.slug = slug self.respawn = respawn sel...
class ManagedGstreamer(ManagedApplication):
""" Instance corresponds to a gstreamer application managed entity. """ def __init__(self, url, slug, window, respawn=True, extra_args=''): self.window = window self.url = url self.slug = slug self.respawn = respawn self.extra_args = extra_args super(Man...
String from lg_msg_defs.msg import WindowGeometry from appctl_support import ProcController from lg_msg_defs.msg import ApplicationState from lg_msg_defs.srv import MediaAppsInfoResponse from lg_common.helpers import get_app_instances_ids from lg_common import ManagedApplication, ManagedWindow from lg_common.helpers i...
127
128
427
9
118
constantegonzalez/lg_ros_nodes
lg_media/src/lg_media/gstreamer_pool.py
Python
ManagedGstreamer
ManagedGstreamer
23
80
23
23
ced00cb8abec5732f6ce021f8b9947ed45a3ff4d
bigcode/the-stack
train
e1261ba94602900881bd161a
train
class
class GstreamerPool(object): """ Manages pool of GstreamerInstances in self.gstreamers dict(id => GstreamerInstance) """ def __init__(self, viewport_name): self.gstreamers = {} # key: app id, value: GstreamerInstance self.viewport_name = viewport_name self.lock = threading....
class GstreamerPool(object):
""" Manages pool of GstreamerInstances in self.gstreamers dict(id => GstreamerInstance) """ def __init__(self, viewport_name): self.gstreamers = {} # key: app id, value: GstreamerInstance self.viewport_name = viewport_name self.lock = threading.Lock() rospy.on_shutd...
(self.state, self.url) return r def _build_cmd(self): cmd = [] cmd.extend([rospy.get_param("~application_path", DEFAULT_APP)]) cmd.extend(rospy.get_param("~application_flags", DEFAULT_ARGS).split()) if self.extra_args != '': cmd.extend(self.extra_args.split()) ...
256
256
1,098
7
249
constantegonzalez/lg_ros_nodes
lg_media/src/lg_media/gstreamer_pool.py
Python
GstreamerPool
GstreamerPool
83
206
83
83
ea4ff4825db9d8327d32dc91920e9342da09f6c5
bigcode/the-stack
train
0d3c8a15689e248331d6756a
train
function
def _get_vhd_parent_uuid(session, vdi_ref, vdi_rec=None): if vdi_rec is None: vdi_rec = session.call_xenapi("VDI.get_record", vdi_ref) if 'vhd-parent' not in vdi_rec['sm_config']: return None parent_uuid = vdi_rec['sm_config']['vhd-parent'] vdi_uuid = vdi_rec['uuid'] LOG.debug('VHD...
def _get_vhd_parent_uuid(session, vdi_ref, vdi_rec=None):
if vdi_rec is None: vdi_rec = session.call_xenapi("VDI.get_record", vdi_ref) if 'vhd-parent' not in vdi_rec['sm_config']: return None parent_uuid = vdi_rec['sm_config']['vhd-parent'] vdi_uuid = vdi_rec['uuid'] LOG.debug('VHD %(vdi_uuid)s has parent %(parent_uuid)s', {...
.get_VDI', vbd_ref) if sr_ref == session.call_xenapi('VDI.get_SR', vdi_ref): yield vdi_ref except session.XenAPI.Failure: continue def _get_vhd_parent_uuid(session, vdi_ref, vdi_rec=None):
64
64
132
18
45
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
_get_vhd_parent_uuid
_get_vhd_parent_uuid
1,988
1,999
1,988
1,988
44bb74a0e2a24afc59fef5f34b70b80a7115ad75
bigcode/the-stack
train
fbc434a0b191fd575cf69f19
train
function
def hard_shutdown_vm(session, instance, vm_ref): if is_vm_shutdown(session, vm_ref): LOG.warning("VM already halted, skipping shutdown...", instance=instance) return True LOG.debug("Shutting down VM (hard)", instance=instance) try: session.call_xenapi('VM.hard_sh...
def hard_shutdown_vm(session, instance, vm_ref):
if is_vm_shutdown(session, vm_ref): LOG.warning("VM already halted, skipping shutdown...", instance=instance) return True LOG.debug("Shutting down VM (hard)", instance=instance) try: session.call_xenapi('VM.hard_shutdown', vm_ref) except session.XenAPI.Failur...
instance=instance) try: session.call_xenapi('VM.clean_shutdown', vm_ref) except session.XenAPI.Failure: LOG.exception(_('Shutting down VM (cleanly) failed.')) return False return True def hard_shutdown_vm(session, instance, vm_ref):
64
64
104
11
52
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
hard_shutdown_vm
hard_shutdown_vm
288
300
288
288
01c252d942263a9ae6bae1a9b7d7f2cf7e1c8513
bigcode/the-stack
train
777f70687536d0b19deec0d9
train
function
def _get_all_vdis_in_sr(session, sr_ref): for vdi_ref in session.call_xenapi('SR.get_VDIs', sr_ref): vdi_rec = session.get_rec('VDI', vdi_ref) # Check to make sure the record still exists. It may have # been deleted between the get_all call and get_rec call if vdi_rec: yi...
def _get_all_vdis_in_sr(session, sr_ref):
for vdi_ref in session.call_xenapi('SR.get_VDIs', sr_ref): vdi_rec = session.get_rec('VDI', vdi_ref) # Check to make sure the record still exists. It may have # been deleted between the get_all call and get_rec call if vdi_rec: yield vdi_ref, vdi_rec
.read() except IOError: LOG.exception(_('Unable to obtain RRD XML for VM %(vm_uuid)s with ' 'server details: %(server)s.'), {'vm_uuid': vm_uuid, 'server': server}) return None def _get_all_vdis_in_sr(session, sr_ref):
64
64
95
13
50
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
_get_all_vdis_in_sr
_get_all_vdis_in_sr
1,968
1,974
1,968
1,968
4f1a4606fd7f3f2ada9e99985ec8e7c2dd375692
bigcode/the-stack
train
74b141fe8b21de7f6c811d1e
train
function
def _add_cpu_usage(session, vm_ref, diag_obj): cpu_num = int(session.VM.get_VCPUs_max(vm_ref)) for cpu_num in range(0, cpu_num): utilisation = _vm_query_data_source(session, vm_ref, "cpu%d" % cpu_num) if utilisation is not None: utilisation *= 100 diag_obj.add_cpu(id=cpu_num,...
def _add_cpu_usage(session, vm_ref, diag_obj):
cpu_num = int(session.VM.get_VCPUs_max(vm_ref)) for cpu_num in range(0, cpu_num): utilisation = _vm_query_data_source(session, vm_ref, "cpu%d" % cpu_num) if utilisation is not None: utilisation *= 100 diag_obj.add_cpu(id=cpu_num, utilisation=utilisation)
vm_ref, diags) _add_nic_usage(session, vm_ref, diags) _add_disk_usage(session, vm_ref, diags) _add_memory_usage(session, vm_ref, diags) return diags def _add_cpu_usage(session, vm_ref, diag_obj):
64
64
90
13
50
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
_add_cpu_usage
_add_cpu_usage
1,732
1,738
1,732
1,732
0cbba45c6d24dd71fe8521c531e163395fa5d57a
bigcode/the-stack
train
2338a941b3a8c6041870dec0
train
function
def safe_destroy_vdis(session, vdi_refs): """Tries to destroy the requested VDIs, but ignores any errors.""" for vdi_ref in vdi_refs: try: destroy_vdi(session, vdi_ref) except exception.StorageError: LOG.debug("Ignoring error while destroying VDI: %s", vdi_ref)
def safe_destroy_vdis(session, vdi_refs):
"""Tries to destroy the requested VDIs, but ignores any errors.""" for vdi_ref in vdi_refs: try: destroy_vdi(session, vdi_ref) except exception.StorageError: LOG.debug("Ignoring error while destroying VDI: %s", vdi_ref)
ailure: LOG.debug("Unable to destroy VDI %s", vdi_ref, exc_info=True) msg = _("Unable to destroy VDI %s") % vdi_ref LOG.error(msg) raise exception.StorageError(reason=msg) def safe_destroy_vdis(session, vdi_refs):
64
64
74
11
53
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
safe_destroy_vdis
safe_destroy_vdis
439
445
439
439
a638b378ff2152111dda8f335d53dae88d400c6a
bigcode/the-stack
train
f57a8b674affa7f3c056d605
train
function
def _copy_partition(session, src_ref, dst_ref, partition, virtual_size): # Part of disk taken up by MBR virtual_size -= MBR_SIZE_BYTES with vdi_attached(session, src_ref, read_only=True) as src: src_path = utils.make_dev_path(src, partition=partition) with vdi_attached(session, dst_ref, re...
def _copy_partition(session, src_ref, dst_ref, partition, virtual_size): # Part of disk taken up by MBR
virtual_size -= MBR_SIZE_BYTES with vdi_attached(session, src_ref, read_only=True) as src: src_path = utils.make_dev_path(src, partition=partition) with vdi_attached(session, dst_ref, read_only=False) as dst: dst_path = utils.make_dev_path(dst, partition=partition) _wr...
_copy in %(duration).2f secs, " "%(compression_pct).2f%% reduction in size", {'duration': duration, 'compression_pct': compression_pct}) def _copy_partition(session, src_ref, dst_ref, partition, virtual_size): # Part of disk taken up by MBR
64
64
175
28
36
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
_copy_partition
_copy_partition
2,377
2,394
2,377
2,378
04a9a3eaad0b62320f18b0e522e2b1026994901c
bigcode/the-stack
train
d3408e8e512af04626eb3a74
train
function
def get_sr_path(session, sr_ref=None): """Return the path to our storage repository This is used when we're dealing with VHDs directly, either by taking snapshots or by restoring an image in the DISK_VHD format. """ if sr_ref is None: sr_ref = safe_find_sr(session) pbd_rec = session.cal...
def get_sr_path(session, sr_ref=None):
"""Return the path to our storage repository This is used when we're dealing with VHDs directly, either by taking snapshots or by restoring an image in the DISK_VHD format. """ if sr_ref is None: sr_ref = safe_find_sr(session) pbd_rec = session.call_xenapi("PBD.get_all_records_where", ...
_walk_vdi_chain(session, snapshot_uuid) vdi_uuids = [vdi_rec['uuid'] for vdi_rec in chain] yield vdi_uuids finally: safe_destroy_vdis(session, [snapshot_ref]) # TODO(johngarbut) we need to check the snapshot has been coalesced # now its associated VDI has been deleted. def g...
95
95
317
10
85
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
get_sr_path
get_sr_path
702
730
702
702
24add8b2aa8d61bd2efa5641904f457059f5290b
bigcode/the-stack
train
9d48d9e5d1211369ff279377
train
function
def destroy_cached_images(session, sr_ref, all_cached=False, dry_run=False, keep_days=0): """Destroy used or unused cached images. A cached image that is being used by at least one VM is said to be 'used'. In the case of an 'unused' image, the cached image will be the only de...
def destroy_cached_images(session, sr_ref, all_cached=False, dry_run=False, keep_days=0):
"""Destroy used or unused cached images. A cached image that is being used by at least one VM is said to be 'used'. In the case of an 'unused' image, the cached image will be the only descendent of the base-copy. So when we delete the cached-image, the refcount will drop to zero and XenServer will...
_config = pbd_rec[pbd_ref]['device_config'] if 'path' in device_config: return device_config['path'] sr_rec = session.call_xenapi("SR.get_record", sr_ref) sr_uuid = sr_rec["uuid"] if sr_rec["type"] not in ["ext", "nfs"]: raise exception.NovaException( _("Only file-based SRs ...
167
167
558
23
144
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
destroy_cached_images
destroy_cached_images
733
792
733
734
b8a8987a4e2b52503c1042b85e72256665649558
bigcode/the-stack
train
ee0df83fdf032c9df2e02599
train
function
def strip_base_mirror_from_vdis(session, vm_ref): # NOTE(johngarbutt) part of workaround for XenServer bug CA-98606 vbd_refs = session.call_xenapi("VM.get_VBDs", vm_ref) for vbd_ref in vbd_refs: vdi_ref = session.call_xenapi("VBD.get_VDI", vbd_ref) _try_strip_base_mirror_from_vdi(session, vd...
def strip_base_mirror_from_vdis(session, vm_ref): # NOTE(johngarbutt) part of workaround for XenServer bug CA-98606
vbd_refs = session.call_xenapi("VM.get_VBDs", vm_ref) for vbd_ref in vbd_refs: vdi_ref = session.call_xenapi("VBD.get_VDI", vbd_ref) _try_strip_base_mirror_from_vdi(session, vdi_ref)
"base_mirror") except session.XenAPI.Failure: LOG.debug("Error while removing sm_config", exc_info=True) def strip_base_mirror_from_vdis(session, vm_ref): # NOTE(johngarbutt) part of workaround for XenServer bug CA-98606
64
64
102
35
29
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
strip_base_mirror_from_vdis
strip_base_mirror_from_vdis
614
619
614
615
0fe641eb1f84c55f906154ff57b1975c2e586349
bigcode/the-stack
train
f9c5dc9f486898a797a42f0d
train
function
def destroy_kernel_ramdisk(session, instance, kernel, ramdisk): if kernel or ramdisk: LOG.debug("Removing kernel/ramdisk files from dom0", instance=instance) disk_management.remove_kernel_ramdisk( session, kernel_file=kernel, ramdisk_file=ramdisk)
def destroy_kernel_ramdisk(session, instance, kernel, ramdisk):
if kernel or ramdisk: LOG.debug("Removing kernel/ramdisk files from dom0", instance=instance) disk_management.remove_kernel_ramdisk( session, kernel_file=kernel, ramdisk_file=ramdisk)
_kernel_image(context, session, instance, name_label, instance['ramdisk_id'], ImageType.RAMDISK) ramdisk_file = vdis['ramdisk'].get('file') return kernel_file, ramdisk_file def destroy_kernel_ramdisk(session, instance, kernel, ramdisk):
64
64
63
14
49
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
destroy_kernel_ramdisk
destroy_kernel_ramdisk
1,217
1,222
1,217
1,217
a2425f02937103d6427b924b525c65a840c07e79
bigcode/the-stack
train
b5d5202cd0332aa1e2e78084
train
function
def compile_instance_diagnostics(session, instance, vm_ref): xen_power_state = session.VM.get_power_state(vm_ref) vm_power_state = power_state.STATE_MAP[XENAPI_POWER_STATE[xen_power_state]] config_drive = configdrive.required_by(instance) diags = diagnostics.Diagnostics(state=vm_power_state, ...
def compile_instance_diagnostics(session, instance, vm_ref):
xen_power_state = session.VM.get_power_state(vm_ref) vm_power_state = power_state.STATE_MAP[XENAPI_POWER_STATE[xen_power_state]] config_drive = configdrive.required_by(instance) diags = diagnostics.Diagnostics(state=vm_power_state, driver='xenapi', ...
.Failure: return None if math.isnan(value): return None return value def compile_info(session, vm_ref): """Fill record with VM status information.""" return hardware.InstanceInfo(state=get_power_state(session, vm_ref)) def compile_instance_diagnostics(session, instance, vm_ref):
64
64
138
12
52
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
compile_instance_diagnostics
compile_instance_diagnostics
1,716
1,729
1,716
1,716
17a3ca871ce24957ff8b7a1edb014e6645da2e2d
bigcode/the-stack
train
29ae60fa9df43f53a28925c0
train
function
def _try_strip_base_mirror_from_vdi(session, vdi_ref): try: session.call_xenapi("VDI.remove_from_sm_config", vdi_ref, "base_mirror") except session.XenAPI.Failure: LOG.debug("Error while removing sm_config", exc_info=True)
def _try_strip_base_mirror_from_vdi(session, vdi_ref):
try: session.call_xenapi("VDI.remove_from_sm_config", vdi_ref, "base_mirror") except session.XenAPI.Failure: LOG.debug("Error while removing sm_config", exc_info=True)
_get_rec(session, vbd_ref) if int(vbd_rec['userdevice']) >= min_userdevice: vdi_ref = vbd_rec['VDI'] yield _vdi_get_uuid(session, vdi_ref) def _try_strip_base_mirror_from_vdi(session, vdi_ref):
64
64
66
16
48
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
_try_strip_base_mirror_from_vdi
_try_strip_base_mirror_from_vdi
606
611
606
606
589fbbc2a0c74ec93ab47bcf90295494ad3d7075
bigcode/the-stack
train
88d1a391837276f2e8f265f3
train
function
def import_all_migrated_disks(session, instance, import_root=True): root_vdi = None if import_root: root_vdi = _import_migrated_root_disk(session, instance) eph_vdis = _import_migrate_ephemeral_disks(session, instance) return {'root': root_vdi, 'ephemerals': eph_vdis}
def import_all_migrated_disks(session, instance, import_root=True):
root_vdi = None if import_root: root_vdi = _import_migrated_root_disk(session, instance) eph_vdis = _import_migrate_ephemeral_disks(session, instance) return {'root': root_vdi, 'ephemerals': eph_vdis}
except session.XenAPI.Failure as exc: if exc.details[0] != 'UUID_INVALID': raise raise Exception(_('This domU must be running on the host ' 'specified by connection_url')) def import_all_migrated_disks(session, instance, import_root=True):
63
64
79
16
47
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
import_all_migrated_disks
import_all_migrated_disks
2,460
2,465
2,460
2,460
a1b6bd7e7e08cba1802669f7ec1832e4a63281b2
bigcode/the-stack
train
c29dba535e1fae5382ea0e9c
train
function
def _import_migrated_root_disk(session, instance): chain_label = instance['uuid'] vdi_label = instance['name'] return _import_migrated_vhds(session, instance, chain_label, "root", vdi_label)
def _import_migrated_root_disk(session, instance):
chain_label = instance['uuid'] vdi_label = instance['name'] return _import_migrated_vhds(session, instance, chain_label, "root", vdi_label)
: root_vdi = _import_migrated_root_disk(session, instance) eph_vdis = _import_migrate_ephemeral_disks(session, instance) return {'root': root_vdi, 'ephemerals': eph_vdis} def _import_migrated_root_disk(session, instance):
64
64
54
12
52
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
_import_migrated_root_disk
_import_migrated_root_disk
2,468
2,472
2,468
2,468
67fea0b3c6ba6709e2a2a20d233cc138b377960c
bigcode/the-stack
train
99bbbc5c0c846846bf4cae68
train
function
@contextlib.contextmanager def snapshot_attached_here(session, instance, vm_ref, label, userdevice='0', post_snapshot_callback=None): # impl method allow easier patching for tests return _snapshot_attached_here_impl(session, instance, vm_ref, label, ...
@contextlib.contextmanager def snapshot_attached_here(session, instance, vm_ref, label, userdevice='0', post_snapshot_callback=None): # impl method allow easier patching for tests
return _snapshot_attached_here_impl(session, instance, vm_ref, label, userdevice, post_snapshot_callback)
"] _delete_snapshots_in_vdi_chain(session, instance, vdi_uuid_chain, sr_ref) @contextlib.contextmanager def snapshot_attached_here(session, instance, vm_ref, label, userdevice='0', post_snapshot_callback=None): # impl method allow easier patching for tests
64
64
67
42
22
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
snapshot_attached_here
snapshot_attached_here
657
662
657
660
bec5719d0084a808e8b97d5e1f5b5434613478a3
bigcode/the-stack
train
cd163791af3b1585e283eaa7
train
function
def determine_vm_mode(instance, disk_image_type): current_mode = obj_fields.VMMode.get_from_instance(instance) if (current_mode == obj_fields.VMMode.XEN or current_mode == obj_fields.VMMode.HVM): return current_mode os_type = instance['os_type'] if os_type == "linux": return obj...
def determine_vm_mode(instance, disk_image_type):
current_mode = obj_fields.VMMode.get_from_instance(instance) if (current_mode == obj_fields.VMMode.XEN or current_mode == obj_fields.VMMode.HVM): return current_mode os_type = instance['os_type'] if os_type == "linux": return obj_fields.VMMode.XEN if os_type == "windows": ...
Error: raise exception.InvalidDiskFormat(disk_format=image_meta.disk_format) LOG.debug("Detected %(type)s format for image %(image)s", {'type': ImageType.to_string(image_type), 'image': image_meta}) return image_type def determine_vm_mode(instance, disk_image_type):
64
64
166
10
53
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
determine_vm_mode
determine_vm_mode
1,579
1,597
1,579
1,579
1b0bac6a7112ce58c1eb3a80311c887b696597e6
bigcode/the-stack
train
c3519be02098598ed871ae70
train
function
def set_vm_name_label(session, vm_ref, name_label): session.call_xenapi("VM.set_name_label", vm_ref, name_label)
def set_vm_name_label(session, vm_ref, name_label):
session.call_xenapi("VM.set_name_label", vm_ref, name_label)
_image_type == ImageType.DISK_VHD or \ disk_image_type == ImageType.DISK: return obj_fields.VMMode.XEN # most images run OK as HVM return obj_fields.VMMode.HVM def set_vm_name_label(session, vm_ref, name_label):
64
64
31
13
50
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
set_vm_name_label
set_vm_name_label
1,600
1,601
1,600
1,600
482ac368a7b843d35d874f51c30aa45c86d7a681
bigcode/the-stack
train
90d11451b4aa2b41eb7f9bc3
train
function
def _clone_vdi(session, vdi_to_clone_ref): """Clones a VDI and return the new VDIs reference.""" vdi_ref = session.call_xenapi('VDI.clone', vdi_to_clone_ref) LOG.debug('Cloned VDI %(vdi_ref)s from VDI ' '%(vdi_to_clone_ref)s', {'vdi_ref': vdi_ref, 'vdi_to_clone_ref': vdi_to_clone...
def _clone_vdi(session, vdi_to_clone_ref):
"""Clones a VDI and return the new VDIs reference.""" vdi_ref = session.call_xenapi('VDI.clone', vdi_to_clone_ref) LOG.debug('Cloned VDI %(vdi_ref)s from VDI ' '%(vdi_to_clone_ref)s', {'vdi_ref': vdi_ref, 'vdi_to_clone_ref': vdi_to_clone_ref}) return vdi_ref
_vhds['root']['uuid'] # rescan to discover new VHDs scan_default_sr(session) vdi_ref = session.call_xenapi('VDI.get_by_uuid', root_uuid) return vdi_ref def _clone_vdi(session, vdi_to_clone_ref):
64
64
105
13
50
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
_clone_vdi
_clone_vdi
523
529
523
523
e864edf8f47fdf50e42075798c2ac848d15d71be
bigcode/the-stack
train
c651638e2d323635ed3fd046
train
function
def get_ephemeral_disk_sizes(total_size_gb): if not total_size_gb: return max_size_gb = 2000 if total_size_gb % 1024 == 0: max_size_gb = 1024 left_to_allocate = total_size_gb while left_to_allocate > 0: size_gb = min(max_size_gb, left_to_allocate) yield size_gb ...
def get_ephemeral_disk_sizes(total_size_gb):
if not total_size_gb: return max_size_gb = 2000 if total_size_gb % 1024 == 0: max_size_gb = 1024 left_to_allocate = total_size_gb while left_to_allocate > 0: size_gb = min(max_size_gb, left_to_allocate) yield size_gb left_to_allocate -= size_gb
raise exception.NotSupportedWithOption( operation='swap drives for Windows', option='CONF.xenserver.independent_compute') _generate_disk(session, instance, vm_ref, userdevice, name_label, 'swap', swap_mb, fs_type) def get_ephemeral_disk_sizes(total_size_gb):
64
64
105
11
53
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
get_ephemeral_disk_sizes
get_ephemeral_disk_sizes
1,075
1,087
1,075
1,075
89409745ed405a7f421b6502dbf2d447229aa5d4
bigcode/the-stack
train
31a4611cfd21c868cde0d966
train
function
def _auto_configure_disk(session, vdi_ref, new_gb): """Partition and resize FS to match the size specified by flavors.root_gb. This is a fail-safe to prevent accidentally destroying data on a disk erroneously marked as auto_disk_config=True. The criteria for allowing resize are: 1. 'auto_...
def _auto_configure_disk(session, vdi_ref, new_gb):
"""Partition and resize FS to match the size specified by flavors.root_gb. This is a fail-safe to prevent accidentally destroying data on a disk erroneously marked as auto_disk_config=True. The criteria for allowing resize are: 1. 'auto_disk_config' must be true for the instance (and imag...
create_vdi(session, sr_ref, instance, instance['name'], 'root', vdi_size) new_uuid = session.call_xenapi('VDI.get_uuid', new_ref) # Manually copy contents over virtual_size = size_gb * units.Gi _copy_partition(session, clone_ref, new_ref, 1, virtual_size) ...
114
114
380
16
98
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
_auto_configure_disk
_auto_configure_disk
921
962
921
921
41b5cd50517d0954111a61a8fd396843f622742f
bigcode/the-stack
train
4b449e90507d2c0dbc6bce9d
train
function
def lookup_vm_vdis(session, vm_ref): """Look for the VDIs that are attached to the VM.""" # Firstly we get the VBDs, then the VDIs. # TODO(Armando): do we leave the read-only devices? vbd_refs = session.call_xenapi("VM.get_VBDs", vm_ref) vdi_refs = [] if vbd_refs: for vbd_ref in vbd_refs...
def lookup_vm_vdis(session, vm_ref):
"""Look for the VDIs that are attached to the VM.""" # Firstly we get the VBDs, then the VDIs. # TODO(Armando): do we leave the read-only devices? vbd_refs = session.call_xenapi("VM.get_VBDs", vm_ref) vdi_refs = [] if vbd_refs: for vbd_ref in vbd_refs: try: vd...
", 'field "is_control_domain"="false" and ' 'field "is_a_template"="false" and ' 'field "resident_on"="%s"' % session.host_ref) for vm_ref in vms.keys(): yield vm_ref, vms[vm_ref] def lookup_vm_vdis(session, vm_ref):
72
72
243
10
62
mertakozcan/nova
nova/virt/xenapi/vm_utils.py
Python
lookup_vm_vdis
lookup_vm_vdis
1,613
1,633
1,613
1,613
b4926d785d64a7a0701985409cb3a49480280077
bigcode/the-stack
train