body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
b870dc88f78c349394b12b75d50ece15b4c8b1107a6e95da470b843b42226794
def test_masked_dict(test_file_name, compression_kwargs): ' Test dictionaries with masked arrays ' (filename, mode) = ('test.h5', 'w') dd = {'data': np.ma.array([1, 2, 3], mask=[True, False, False]), 'data2': np.array([1, 2, 3, 4, 5])} dump(dd, test_file_name, mode, **compression_kwargs) dd_hkl = load(test_file_name) for k in dd.keys(): try: assert (k in dd_hkl.keys()) if isinstance(dd[k], np.ndarray): assert np.all((dd[k], dd_hkl[k])) elif isinstance(dd[k], np.ma.MaskedArray): print(dd[k].data) print(dd_hkl[k].data) assert np.allclose(dd[k].data, dd_hkl[k].data) assert np.allclose(dd[k].mask, dd_hkl[k].mask) assert isinstance(dd_hkl[k], dd[k].__class__) except AssertionError: print(k) print(dd_hkl[k]) print(dd[k]) print(type(dd_hkl[k]), type(dd[k])) raise
Test dictionaries with masked arrays
hickle/tests/test_hickle.py
test_masked_dict
texadactyl/hickle
0
python
def test_masked_dict(test_file_name, compression_kwargs): ' ' (filename, mode) = ('test.h5', 'w') dd = {'data': np.ma.array([1, 2, 3], mask=[True, False, False]), 'data2': np.array([1, 2, 3, 4, 5])} dump(dd, test_file_name, mode, **compression_kwargs) dd_hkl = load(test_file_name) for k in dd.keys(): try: assert (k in dd_hkl.keys()) if isinstance(dd[k], np.ndarray): assert np.all((dd[k], dd_hkl[k])) elif isinstance(dd[k], np.ma.MaskedArray): print(dd[k].data) print(dd_hkl[k].data) assert np.allclose(dd[k].data, dd_hkl[k].data) assert np.allclose(dd[k].mask, dd_hkl[k].mask) assert isinstance(dd_hkl[k], dd[k].__class__) except AssertionError: print(k) print(dd_hkl[k]) print(dd[k]) print(type(dd_hkl[k]), type(dd[k])) raise
def test_masked_dict(test_file_name, compression_kwargs): ' ' (filename, mode) = ('test.h5', 'w') dd = {'data': np.ma.array([1, 2, 3], mask=[True, False, False]), 'data2': np.array([1, 2, 3, 4, 5])} dump(dd, test_file_name, mode, **compression_kwargs) dd_hkl = load(test_file_name) for k in dd.keys(): try: assert (k in dd_hkl.keys()) if isinstance(dd[k], np.ndarray): assert np.all((dd[k], dd_hkl[k])) elif isinstance(dd[k], np.ma.MaskedArray): print(dd[k].data) print(dd_hkl[k].data) assert np.allclose(dd[k].data, dd_hkl[k].data) assert np.allclose(dd[k].mask, dd_hkl[k].mask) assert isinstance(dd_hkl[k], dd[k].__class__) except AssertionError: print(k) print(dd_hkl[k]) print(dd[k]) print(type(dd_hkl[k]), type(dd[k])) raise<|docstring|>Test dictionaries with masked arrays<|endoftext|>
bb9717d807484e007ad6f6a543aa473bf0f8abc2b4d00b28103b3063a489d5e6
def test_np_float(test_file_name, compression_kwargs): ' Test for singular np dtypes ' mode = 'w' dtype_list = (np.float16, np.float32, np.float64, np.complex64, np.complex128, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64) for dt in dtype_list: dd = dt(1) dump(dd, test_file_name, mode, **compression_kwargs) dd_hkl = load(test_file_name) assert (dd == dd_hkl) assert (dd.dtype == dd_hkl.dtype) dd = {} for dt in dtype_list: dd[str(dt)] = dt(1.0) dump(dd, test_file_name, mode, **compression_kwargs) dd_hkl = load(test_file_name) print(dd) for dt in dtype_list: assert (dd[str(dt)] == dd_hkl[str(dt)])
Test for singular np dtypes
hickle/tests/test_hickle.py
test_np_float
texadactyl/hickle
0
python
def test_np_float(test_file_name, compression_kwargs): ' ' mode = 'w' dtype_list = (np.float16, np.float32, np.float64, np.complex64, np.complex128, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64) for dt in dtype_list: dd = dt(1) dump(dd, test_file_name, mode, **compression_kwargs) dd_hkl = load(test_file_name) assert (dd == dd_hkl) assert (dd.dtype == dd_hkl.dtype) dd = {} for dt in dtype_list: dd[str(dt)] = dt(1.0) dump(dd, test_file_name, mode, **compression_kwargs) dd_hkl = load(test_file_name) print(dd) for dt in dtype_list: assert (dd[str(dt)] == dd_hkl[str(dt)])
def test_np_float(test_file_name, compression_kwargs): ' ' mode = 'w' dtype_list = (np.float16, np.float32, np.float64, np.complex64, np.complex128, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64) for dt in dtype_list: dd = dt(1) dump(dd, test_file_name, mode, **compression_kwargs) dd_hkl = load(test_file_name) assert (dd == dd_hkl) assert (dd.dtype == dd_hkl.dtype) dd = {} for dt in dtype_list: dd[str(dt)] = dt(1.0) dump(dd, test_file_name, mode, **compression_kwargs) dd_hkl = load(test_file_name) print(dd) for dt in dtype_list: assert (dd[str(dt)] == dd_hkl[str(dt)])<|docstring|>Test for singular np dtypes<|endoftext|>
01e944766f298b97a0c0020d13b17370d824344370002b52eb86b12956f541a4
@pytest.mark.no_compression def test_comp_kwargs(test_file_name): ' Test compression with some kwargs for shuffle and chunking ' mode = 'w' dtypes = ['int32', 'float32', 'float64', 'complex64', 'complex128'] comps = [None, 'gzip', 'lzf'] chunks = [(100, 100), (250, 250)] shuffles = [True, False] scaleoffsets = [0, 1, 2] for dt in dtypes: for cc in comps: for ch in chunks: for sh in shuffles: for so in scaleoffsets: kwargs = {'compression': cc, 'dtype': dt, 'chunks': ch, 'shuffle': sh, 'scaleoffset': so} array_obj = NESTED_DICT dump(array_obj, test_file_name, mode, compression=cc) print(kwargs, os.path.getsize(test_file_name)) load(test_file_name)
Test compression with some kwargs for shuffle and chunking
hickle/tests/test_hickle.py
test_comp_kwargs
texadactyl/hickle
0
python
@pytest.mark.no_compression def test_comp_kwargs(test_file_name): ' ' mode = 'w' dtypes = ['int32', 'float32', 'float64', 'complex64', 'complex128'] comps = [None, 'gzip', 'lzf'] chunks = [(100, 100), (250, 250)] shuffles = [True, False] scaleoffsets = [0, 1, 2] for dt in dtypes: for cc in comps: for ch in chunks: for sh in shuffles: for so in scaleoffsets: kwargs = {'compression': cc, 'dtype': dt, 'chunks': ch, 'shuffle': sh, 'scaleoffset': so} array_obj = NESTED_DICT dump(array_obj, test_file_name, mode, compression=cc) print(kwargs, os.path.getsize(test_file_name)) load(test_file_name)
@pytest.mark.no_compression def test_comp_kwargs(test_file_name): ' ' mode = 'w' dtypes = ['int32', 'float32', 'float64', 'complex64', 'complex128'] comps = [None, 'gzip', 'lzf'] chunks = [(100, 100), (250, 250)] shuffles = [True, False] scaleoffsets = [0, 1, 2] for dt in dtypes: for cc in comps: for ch in chunks: for sh in shuffles: for so in scaleoffsets: kwargs = {'compression': cc, 'dtype': dt, 'chunks': ch, 'shuffle': sh, 'scaleoffset': so} array_obj = NESTED_DICT dump(array_obj, test_file_name, mode, compression=cc) print(kwargs, os.path.getsize(test_file_name)) load(test_file_name)<|docstring|>Test compression with some kwargs for shuffle and chunking<|endoftext|>
66e1dd2043835d7121e82990554aeb67e5410e9b8867b3f47cad707a04ed9254
def test_list_numpy(test_file_name, compression_kwargs): ' Test converting a list of numpy arrays ' mode = 'w' a = np.ones(1024) b = np.zeros(1000) c = [a, b] dump(c, test_file_name, mode, **compression_kwargs) dd_hkl = load(test_file_name) print(dd_hkl) assert isinstance(dd_hkl, list) assert isinstance(dd_hkl[0], np.ndarray)
Test converting a list of numpy arrays
hickle/tests/test_hickle.py
test_list_numpy
texadactyl/hickle
0
python
def test_list_numpy(test_file_name, compression_kwargs): ' ' mode = 'w' a = np.ones(1024) b = np.zeros(1000) c = [a, b] dump(c, test_file_name, mode, **compression_kwargs) dd_hkl = load(test_file_name) print(dd_hkl) assert isinstance(dd_hkl, list) assert isinstance(dd_hkl[0], np.ndarray)
def test_list_numpy(test_file_name, compression_kwargs): ' ' mode = 'w' a = np.ones(1024) b = np.zeros(1000) c = [a, b] dump(c, test_file_name, mode, **compression_kwargs) dd_hkl = load(test_file_name) print(dd_hkl) assert isinstance(dd_hkl, list) assert isinstance(dd_hkl[0], np.ndarray)<|docstring|>Test converting a list of numpy arrays<|endoftext|>
65d4f2afdf26361480a97a69186f4add451067f98b2245052d5ac560976caed2
def test_tuple_numpy(test_file_name, compression_kwargs): ' Test converting a list of numpy arrays ' mode = 'w' a = np.ones(1024) b = np.zeros(1000) c = (a, b, a) dump(c, test_file_name, mode, **compression_kwargs) dd_hkl = load(test_file_name) print(dd_hkl) assert isinstance(dd_hkl, tuple) assert isinstance(dd_hkl[0], np.ndarray)
Test converting a list of numpy arrays
hickle/tests/test_hickle.py
test_tuple_numpy
texadactyl/hickle
0
python
def test_tuple_numpy(test_file_name, compression_kwargs): ' ' mode = 'w' a = np.ones(1024) b = np.zeros(1000) c = (a, b, a) dump(c, test_file_name, mode, **compression_kwargs) dd_hkl = load(test_file_name) print(dd_hkl) assert isinstance(dd_hkl, tuple) assert isinstance(dd_hkl[0], np.ndarray)
def test_tuple_numpy(test_file_name, compression_kwargs): ' ' mode = 'w' a = np.ones(1024) b = np.zeros(1000) c = (a, b, a) dump(c, test_file_name, mode, **compression_kwargs) dd_hkl = load(test_file_name) print(dd_hkl) assert isinstance(dd_hkl, tuple) assert isinstance(dd_hkl[0], np.ndarray)<|docstring|>Test converting a list of numpy arrays<|endoftext|>
20791e1877f83c73f1b3a4a721210f6d2272c08d452a3f6100d924d3e671d28c
def test_numpy_dtype(test_file_name, compression_kwargs): ' Dumping and loading a NumPy dtype ' dtype = np.dtype('int64') dump(dtype, test_file_name, **compression_kwargs) dtype_hkl = load(test_file_name) assert (dtype == dtype_hkl)
Dumping and loading a NumPy dtype
hickle/tests/test_hickle.py
test_numpy_dtype
texadactyl/hickle
0
python
def test_numpy_dtype(test_file_name, compression_kwargs): ' ' dtype = np.dtype('int64') dump(dtype, test_file_name, **compression_kwargs) dtype_hkl = load(test_file_name) assert (dtype == dtype_hkl)
def test_numpy_dtype(test_file_name, compression_kwargs): ' ' dtype = np.dtype('int64') dump(dtype, test_file_name, **compression_kwargs) dtype_hkl = load(test_file_name) assert (dtype == dtype_hkl)<|docstring|>Dumping and loading a NumPy dtype<|endoftext|>
c3527647053a85de5763c952e6815d3fb7ebc1fb856a008ff3e1d2f1ec593578
def test_none(test_file_name, compression_kwargs): ' Test None type hickling ' mode = 'w' a = None dump(a, test_file_name, mode, **compression_kwargs) dd_hkl = load(test_file_name) print(a) print(dd_hkl) assert isinstance(dd_hkl, type(None))
Test None type hickling
hickle/tests/test_hickle.py
test_none
texadactyl/hickle
0
python
def test_none(test_file_name, compression_kwargs): ' ' mode = 'w' a = None dump(a, test_file_name, mode, **compression_kwargs) dd_hkl = load(test_file_name) print(a) print(dd_hkl) assert isinstance(dd_hkl, type(None))
def test_none(test_file_name, compression_kwargs): ' ' mode = 'w' a = None dump(a, test_file_name, mode, **compression_kwargs) dd_hkl = load(test_file_name) print(a) print(dd_hkl) assert isinstance(dd_hkl, type(None))<|docstring|>Test None type hickling<|endoftext|>
29c92c81f7ef68aafb9ba81b3d5c30dc5d118ee11cb37bf8d19c6830e0b969ce
def test_list_order(test_file_name, compression_kwargs): ' https://github.com/telegraphic/hickle/issues/26 ' d = [np.arange((n + 1)) for n in range(20)] dump(d, test_file_name, **compression_kwargs) d_hkl = load(test_file_name) try: for (ii, xx) in enumerate(d): assert (d[ii].shape == d_hkl[ii].shape) for (ii, xx) in enumerate(d): assert np.allclose(d[ii], d_hkl[ii]) except AssertionError: print(d[ii], d_hkl[ii]) raise
https://github.com/telegraphic/hickle/issues/26
hickle/tests/test_hickle.py
test_list_order
texadactyl/hickle
0
python
def test_list_order(test_file_name, compression_kwargs): ' ' d = [np.arange((n + 1)) for n in range(20)] dump(d, test_file_name, **compression_kwargs) d_hkl = load(test_file_name) try: for (ii, xx) in enumerate(d): assert (d[ii].shape == d_hkl[ii].shape) for (ii, xx) in enumerate(d): assert np.allclose(d[ii], d_hkl[ii]) except AssertionError: print(d[ii], d_hkl[ii]) raise
def test_list_order(test_file_name, compression_kwargs): ' ' d = [np.arange((n + 1)) for n in range(20)] dump(d, test_file_name, **compression_kwargs) d_hkl = load(test_file_name) try: for (ii, xx) in enumerate(d): assert (d[ii].shape == d_hkl[ii].shape) for (ii, xx) in enumerate(d): assert np.allclose(d[ii], d_hkl[ii]) except AssertionError: print(d[ii], d_hkl[ii]) raise<|docstring|>https://github.com/telegraphic/hickle/issues/26<|endoftext|>
105c631cfaee60e0865916c5749419d7f7486539ffdfca01f5a635b4ff0ab928
def test_embedded_array(test_file_name, compression_kwargs): ' See https://github.com/telegraphic/hickle/issues/24 ' d_orig = [[np.array([10.0, 20.0]), np.array([10, 20, 30])], [np.array([10, 2]), np.array([1.0])]] dump(d_orig, test_file_name, **compression_kwargs) d_hkl = load(test_file_name) for (ii, xx) in enumerate(d_orig): for (jj, yy) in enumerate(xx): assert np.allclose(d_orig[ii][jj], d_hkl[ii][jj]) print(d_hkl) print(d_orig)
See https://github.com/telegraphic/hickle/issues/24
hickle/tests/test_hickle.py
test_embedded_array
texadactyl/hickle
0
python
def test_embedded_array(test_file_name, compression_kwargs): ' ' d_orig = [[np.array([10.0, 20.0]), np.array([10, 20, 30])], [np.array([10, 2]), np.array([1.0])]] dump(d_orig, test_file_name, **compression_kwargs) d_hkl = load(test_file_name) for (ii, xx) in enumerate(d_orig): for (jj, yy) in enumerate(xx): assert np.allclose(d_orig[ii][jj], d_hkl[ii][jj]) print(d_hkl) print(d_orig)
def test_embedded_array(test_file_name, compression_kwargs): ' ' d_orig = [[np.array([10.0, 20.0]), np.array([10, 20, 30])], [np.array([10, 2]), np.array([1.0])]] dump(d_orig, test_file_name, **compression_kwargs) d_hkl = load(test_file_name) for (ii, xx) in enumerate(d_orig): for (jj, yy) in enumerate(xx): assert np.allclose(d_orig[ii][jj], d_hkl[ii][jj]) print(d_hkl) print(d_orig)<|docstring|>See https://github.com/telegraphic/hickle/issues/24<|endoftext|>
5acf2859822e7d5d7d49824690dccf15e9505df22c11edf886537fcc8326a572
def test_dump_nested(test_file_name, compression_kwargs): ' Dump a complicated nested object to HDF5\n ' z = generate_nested() dump(z, test_file_name, mode='w', **compression_kwargs)
Dump a complicated nested object to HDF5
hickle/tests/test_hickle.py
test_dump_nested
texadactyl/hickle
0
python
def test_dump_nested(test_file_name, compression_kwargs): ' \n ' z = generate_nested() dump(z, test_file_name, mode='w', **compression_kwargs)
def test_dump_nested(test_file_name, compression_kwargs): ' \n ' z = generate_nested() dump(z, test_file_name, mode='w', **compression_kwargs)<|docstring|>Dump a complicated nested object to HDF5<|endoftext|>
d2cf21f05328f2b097294721a1d835589e7c0b91f567f1fae8d4ac326dca38eb
def test_complex(test_file_name, compression_kwargs): ' Test complex value dtype is handled correctly\n\n https://github.com/telegraphic/hickle/issues/29 ' data = {'A': 1.5, 'B': (1.5 + 1j), 'C': (np.linspace(0, 1, 4) + 2j)} dump(data, test_file_name, **compression_kwargs) data2 = load(test_file_name) for key in data.keys(): assert isinstance(data[key], data2[key].__class__)
Test complex value dtype is handled correctly https://github.com/telegraphic/hickle/issues/29
hickle/tests/test_hickle.py
test_complex
texadactyl/hickle
0
python
def test_complex(test_file_name, compression_kwargs): ' Test complex value dtype is handled correctly\n\n https://github.com/telegraphic/hickle/issues/29 ' data = {'A': 1.5, 'B': (1.5 + 1j), 'C': (np.linspace(0, 1, 4) + 2j)} dump(data, test_file_name, **compression_kwargs) data2 = load(test_file_name) for key in data.keys(): assert isinstance(data[key], data2[key].__class__)
def test_complex(test_file_name, compression_kwargs): ' Test complex value dtype is handled correctly\n\n https://github.com/telegraphic/hickle/issues/29 ' data = {'A': 1.5, 'B': (1.5 + 1j), 'C': (np.linspace(0, 1, 4) + 2j)} dump(data, test_file_name, **compression_kwargs) data2 = load(test_file_name) for key in data.keys(): assert isinstance(data[key], data2[key].__class__)<|docstring|>Test complex value dtype is handled correctly https://github.com/telegraphic/hickle/issues/29<|endoftext|>
ce6cf2f925dd02e1e41e2060a42435e77ad40e9039a1a8625b1029502bb172f8
def test_nonstring_keys(test_file_name, compression_kwargs): ' Test that keys are reconstructed back to their original datatypes\n https://github.com/telegraphic/hickle/issues/36\n ' data = {u'test': 123, 'def': [b'test'], 'hik': np.array([1, 2, 3]), 0: 0, True: ['test'], 1.1: 'hey', 1j: 'complex_hashable', (1, 2): 'boo', ('A', 17.4, 42): [1, 7, 'A'], (): '1313e was here', '0': 0, None: None} print(data) dump(data, test_file_name, **compression_kwargs) data2 = load(test_file_name) print(data2) for key in data.keys(): assert (key in data2.keys()) print(data2)
Test that keys are reconstructed back to their original datatypes https://github.com/telegraphic/hickle/issues/36
hickle/tests/test_hickle.py
test_nonstring_keys
texadactyl/hickle
0
python
def test_nonstring_keys(test_file_name, compression_kwargs): ' Test that keys are reconstructed back to their original datatypes\n https://github.com/telegraphic/hickle/issues/36\n ' data = {u'test': 123, 'def': [b'test'], 'hik': np.array([1, 2, 3]), 0: 0, True: ['test'], 1.1: 'hey', 1j: 'complex_hashable', (1, 2): 'boo', ('A', 17.4, 42): [1, 7, 'A'], (): '1313e was here', '0': 0, None: None} print(data) dump(data, test_file_name, **compression_kwargs) data2 = load(test_file_name) print(data2) for key in data.keys(): assert (key in data2.keys()) print(data2)
def test_nonstring_keys(test_file_name, compression_kwargs): ' Test that keys are reconstructed back to their original datatypes\n https://github.com/telegraphic/hickle/issues/36\n ' data = {u'test': 123, 'def': [b'test'], 'hik': np.array([1, 2, 3]), 0: 0, True: ['test'], 1.1: 'hey', 1j: 'complex_hashable', (1, 2): 'boo', ('A', 17.4, 42): [1, 7, 'A'], (): '1313e was here', '0': 0, None: None} print(data) dump(data, test_file_name, **compression_kwargs) data2 = load(test_file_name) print(data2) for key in data.keys(): assert (key in data2.keys()) print(data2)<|docstring|>Test that keys are reconstructed back to their original datatypes https://github.com/telegraphic/hickle/issues/36<|endoftext|>
d1dac0f5b16930d3585eeb2170b7f20212fd40c1a7f598a69428e58aaf572e9c
@pytest.mark.no_compression def test_scalar_compression(test_file_name): ' Test bug where compression causes a crash on scalar datasets\n\n (Scalars are incompressible!)\n https://github.com/telegraphic/hickle/issues/37\n ' data = {'a': 0, 'b': float(2), 'c': True} dump(data, test_file_name, compression='gzip') data2 = load(test_file_name) print(data2) for key in data.keys(): assert isinstance(data[key], data2[key].__class__)
Test bug where compression causes a crash on scalar datasets (Scalars are incompressible!) https://github.com/telegraphic/hickle/issues/37
hickle/tests/test_hickle.py
test_scalar_compression
texadactyl/hickle
0
python
@pytest.mark.no_compression def test_scalar_compression(test_file_name): ' Test bug where compression causes a crash on scalar datasets\n\n (Scalars are incompressible!)\n https://github.com/telegraphic/hickle/issues/37\n ' data = {'a': 0, 'b': float(2), 'c': True} dump(data, test_file_name, compression='gzip') data2 = load(test_file_name) print(data2) for key in data.keys(): assert isinstance(data[key], data2[key].__class__)
@pytest.mark.no_compression def test_scalar_compression(test_file_name): ' Test bug where compression causes a crash on scalar datasets\n\n (Scalars are incompressible!)\n https://github.com/telegraphic/hickle/issues/37\n ' data = {'a': 0, 'b': float(2), 'c': True} dump(data, test_file_name, compression='gzip') data2 = load(test_file_name) print(data2) for key in data.keys(): assert isinstance(data[key], data2[key].__class__)<|docstring|>Test bug where compression causes a crash on scalar datasets (Scalars are incompressible!) https://github.com/telegraphic/hickle/issues/37<|endoftext|>
8979b356137c02bccb031c3b3bb89e636bad5c55acdb564f0c6be14cfb6a5afc
def test_bytes(test_file_name, compression_kwargs): ' Dumping and loading a string. PYTHON3 ONLY ' mode = 'w' string_obj = b'The quick brown fox jumps over the lazy dog' dump(string_obj, test_file_name, mode, **compression_kwargs) string_hkl = load(test_file_name) print(type(string_obj)) print(type(string_hkl)) assert isinstance(string_hkl, bytes) assert (string_obj == string_hkl)
Dumping and loading a string. PYTHON3 ONLY
hickle/tests/test_hickle.py
test_bytes
texadactyl/hickle
0
python
def test_bytes(test_file_name, compression_kwargs): ' ' mode = 'w' string_obj = b'The quick brown fox jumps over the lazy dog' dump(string_obj, test_file_name, mode, **compression_kwargs) string_hkl = load(test_file_name) print(type(string_obj)) print(type(string_hkl)) assert isinstance(string_hkl, bytes) assert (string_obj == string_hkl)
def test_bytes(test_file_name, compression_kwargs): ' ' mode = 'w' string_obj = b'The quick brown fox jumps over the lazy dog' dump(string_obj, test_file_name, mode, **compression_kwargs) string_hkl = load(test_file_name) print(type(string_obj)) print(type(string_hkl)) assert isinstance(string_hkl, bytes) assert (string_obj == string_hkl)<|docstring|>Dumping and loading a string. PYTHON3 ONLY<|endoftext|>
f772988f7a113bb01643d515e800877bb114c182cd96a1b97fb7b69971a0664b
def test_np_scalar(test_file_name, compression_kwargs): ' Numpy scalar datatype\n\n https://github.com/telegraphic/hickle/issues/50\n ' r0 = {'test': np.float64(10.0)} dump(r0, test_file_name, **compression_kwargs) r = load(test_file_name) print(r) assert isinstance(r0['test'], r['test'].__class__)
Numpy scalar datatype https://github.com/telegraphic/hickle/issues/50
hickle/tests/test_hickle.py
test_np_scalar
texadactyl/hickle
0
python
def test_np_scalar(test_file_name, compression_kwargs): ' Numpy scalar datatype\n\n https://github.com/telegraphic/hickle/issues/50\n ' r0 = {'test': np.float64(10.0)} dump(r0, test_file_name, **compression_kwargs) r = load(test_file_name) print(r) assert isinstance(r0['test'], r['test'].__class__)
def test_np_scalar(test_file_name, compression_kwargs): ' Numpy scalar datatype\n\n https://github.com/telegraphic/hickle/issues/50\n ' r0 = {'test': np.float64(10.0)} dump(r0, test_file_name, **compression_kwargs) r = load(test_file_name) print(r) assert isinstance(r0['test'], r['test'].__class__)<|docstring|>Numpy scalar datatype https://github.com/telegraphic/hickle/issues/50<|endoftext|>
9c3d2f4dfe5625b1f854af91d06624b6dee9f19fecee5a7a260ec40c02506b6f
def test_slash_dict_keys(test_file_name, compression_kwargs): ' Support for having slashes in dict keys\n\n https://github.com/telegraphic/hickle/issues/124' dct = {'a/b': [1, '2'], 1.4: 3} dump(dct, test_file_name, 'w', **compression_kwargs) dct_hkl = load(test_file_name) assert isinstance(dct_hkl, dict) for (key, val) in dct_hkl.items(): assert (val == dct.get(key)) dct2 = {'a\\b': [1, '2'], 1.4: 3} with pytest.warns(None) as not_expected: dump(dct2, test_file_name, **compression_kwargs) assert (not not_expected)
Support for having slashes in dict keys https://github.com/telegraphic/hickle/issues/124
hickle/tests/test_hickle.py
test_slash_dict_keys
texadactyl/hickle
0
python
def test_slash_dict_keys(test_file_name, compression_kwargs): ' Support for having slashes in dict keys\n\n https://github.com/telegraphic/hickle/issues/124' dct = {'a/b': [1, '2'], 1.4: 3} dump(dct, test_file_name, 'w', **compression_kwargs) dct_hkl = load(test_file_name) assert isinstance(dct_hkl, dict) for (key, val) in dct_hkl.items(): assert (val == dct.get(key)) dct2 = {'a\\b': [1, '2'], 1.4: 3} with pytest.warns(None) as not_expected: dump(dct2, test_file_name, **compression_kwargs) assert (not not_expected)
def test_slash_dict_keys(test_file_name, compression_kwargs): ' Support for having slashes in dict keys\n\n https://github.com/telegraphic/hickle/issues/124' dct = {'a/b': [1, '2'], 1.4: 3} dump(dct, test_file_name, 'w', **compression_kwargs) dct_hkl = load(test_file_name) assert isinstance(dct_hkl, dict) for (key, val) in dct_hkl.items(): assert (val == dct.get(key)) dct2 = {'a\\b': [1, '2'], 1.4: 3} with pytest.warns(None) as not_expected: dump(dct2, test_file_name, **compression_kwargs) assert (not not_expected)<|docstring|>Support for having slashes in dict keys https://github.com/telegraphic/hickle/issues/124<|endoftext|>
1337ed45fdbc1dc339d0d42fe2f3528f0caf38cdf3814f6a37da1841ab439a02
def test_superuser_read_researchgroup_list(self): '\n Test Superuser can read ResearchGroup list\n ' request = self.factory.get(reverse('researchgroup-list')) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'list'})(request) self.assertContains(response=response, text='', status_code=200)
Test Superuser can read ResearchGroup list
api/radiam/api/tests/permissionstests/researchgrouppermissionstests.py
test_superuser_read_researchgroup_list
usask-rc/radiam
2
python
def test_superuser_read_researchgroup_list(self): '\n \n ' request = self.factory.get(reverse('researchgroup-list')) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'list'})(request) self.assertContains(response=response, text=, status_code=200)
def test_superuser_read_researchgroup_list(self): '\n \n ' request = self.factory.get(reverse('researchgroup-list')) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'list'})(request) self.assertContains(response=response, text=, status_code=200)<|docstring|>Test Superuser can read ResearchGroup list<|endoftext|>
1cbb941b1daed83099e25d492ea2c3650eeffa62d2f891146cb360f0b82b019b
def test_superuser_write_researchgroup_list(self): '\n Test Superuser can write ResearchGroup list\n (ie: create new ResearchGroups)\n ' body = {'name': 'testgroup', 'description': 'Some Test Group'} request = self.factory.post(reverse('researchgroup-list'), json.dumps(body), content_type='application/json') request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'post': 'create'})(request) self.assertContains(response=response, text='', status_code=201)
Test Superuser can write ResearchGroup list (ie: create new ResearchGroups)
api/radiam/api/tests/permissionstests/researchgrouppermissionstests.py
test_superuser_write_researchgroup_list
usask-rc/radiam
2
python
def test_superuser_write_researchgroup_list(self): '\n Test Superuser can write ResearchGroup list\n (ie: create new ResearchGroups)\n ' body = {'name': 'testgroup', 'description': 'Some Test Group'} request = self.factory.post(reverse('researchgroup-list'), json.dumps(body), content_type='application/json') request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'post': 'create'})(request) self.assertContains(response=response, text=, status_code=201)
def test_superuser_write_researchgroup_list(self): '\n Test Superuser can write ResearchGroup list\n (ie: create new ResearchGroups)\n ' body = {'name': 'testgroup', 'description': 'Some Test Group'} request = self.factory.post(reverse('researchgroup-list'), json.dumps(body), content_type='application/json') request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'post': 'create'})(request) self.assertContains(response=response, text=, status_code=201)<|docstring|>Test Superuser can write ResearchGroup list (ie: create new ResearchGroups)<|endoftext|>
e8431d8942ee89585c8b54e04f91888680749c32fceb6bfa6b571126cfa3cf65
def test_superuser_read_researchgroup_detail(self): '\n Test Superuser can update an existing research group\n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') request = self.factory.get(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'retrieve'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text='', status_code=200)
Test Superuser can update an existing research group
api/radiam/api/tests/permissionstests/researchgrouppermissionstests.py
test_superuser_read_researchgroup_detail
usask-rc/radiam
2
python
def test_superuser_read_researchgroup_detail(self): '\n \n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') request = self.factory.get(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'retrieve'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=200)
def test_superuser_read_researchgroup_detail(self): '\n \n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') request = self.factory.get(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'retrieve'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=200)<|docstring|>Test Superuser can update an existing research group<|endoftext|>
dbd6aa21faf74ca5c34853580da54d79d950b2229db65850e945f853eae49984
@mock.patch('radiam.api.documents.ResearchGroupMetadataDoc') def test_superuser_write_researchgroup_detail(self, doc): '\n Test Superuser can update an existing research group\n ' doc.get.return_value = doc doc.update.return_value = None detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') body = {'name': 'testgroup', 'description': 'Some Test Group'} request = self.factory.patch(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'patch': 'partial_update'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text='', status_code=200)
Test Superuser can update an existing research group
api/radiam/api/tests/permissionstests/researchgrouppermissionstests.py
test_superuser_write_researchgroup_detail
usask-rc/radiam
2
python
@mock.patch('radiam.api.documents.ResearchGroupMetadataDoc') def test_superuser_write_researchgroup_detail(self, doc): '\n \n ' doc.get.return_value = doc doc.update.return_value = None detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') body = {'name': 'testgroup', 'description': 'Some Test Group'} request = self.factory.patch(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'patch': 'partial_update'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=200)
@mock.patch('radiam.api.documents.ResearchGroupMetadataDoc') def test_superuser_write_researchgroup_detail(self, doc): '\n \n ' doc.get.return_value = doc doc.update.return_value = None detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') body = {'name': 'testgroup', 'description': 'Some Test Group'} request = self.factory.patch(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'patch': 'partial_update'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=200)<|docstring|>Test Superuser can update an existing research group<|endoftext|>
61b6e13a0704b26f0f0439c62d534f7d1c7c9af4fca9ff150b544f722b7af3d1
def test_adminuser_read_researchgroup_list(self): '\n Test Adminuser can read ResearchGroup list. Restricted to groups that\n they admin.\n ' user_groups = self.user.get_groups() request = self.factory.get(reverse('researchgroup-list')) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'list'})(request) self.assertContains(response=response, text='', status_code=200) self.assertEquals(response.data['count'], user_groups.count())
Test Adminuser can read ResearchGroup list. Restricted to groups that they admin.
api/radiam/api/tests/permissionstests/researchgrouppermissionstests.py
test_adminuser_read_researchgroup_list
usask-rc/radiam
2
python
def test_adminuser_read_researchgroup_list(self): '\n Test Adminuser can read ResearchGroup list. Restricted to groups that\n they admin.\n ' user_groups = self.user.get_groups() request = self.factory.get(reverse('researchgroup-list')) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'list'})(request) self.assertContains(response=response, text=, status_code=200) self.assertEquals(response.data['count'], user_groups.count())
def test_adminuser_read_researchgroup_list(self): '\n Test Adminuser can read ResearchGroup list. Restricted to groups that\n they admin.\n ' user_groups = self.user.get_groups() request = self.factory.get(reverse('researchgroup-list')) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'list'})(request) self.assertContains(response=response, text=, status_code=200) self.assertEquals(response.data['count'], user_groups.count())<|docstring|>Test Adminuser can read ResearchGroup list. Restricted to groups that they admin.<|endoftext|>
d556fa0e8f20b2d4604228759b6563c6064a9aee88baafd54ed56a9d2f5637af
def test_adminuser_write_researchgroup_list(self): '\n Test Admin user can write ResearchGroup list\n (ie: create new ResearchGroups)\n ' body = {'name': 'testgroup', 'description': 'Some Test Group'} request = self.factory.post(reverse('researchgroup-list'), json.dumps(body), content_type='application/json') request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'post': 'create'})(request) self.assertContains(response=response, text='', status_code=201)
Test Admin user can write ResearchGroup list (ie: create new ResearchGroups)
api/radiam/api/tests/permissionstests/researchgrouppermissionstests.py
test_adminuser_write_researchgroup_list
usask-rc/radiam
2
python
def test_adminuser_write_researchgroup_list(self): '\n Test Admin user can write ResearchGroup list\n (ie: create new ResearchGroups)\n ' body = {'name': 'testgroup', 'description': 'Some Test Group'} request = self.factory.post(reverse('researchgroup-list'), json.dumps(body), content_type='application/json') request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'post': 'create'})(request) self.assertContains(response=response, text=, status_code=201)
def test_adminuser_write_researchgroup_list(self): '\n Test Admin user can write ResearchGroup list\n (ie: create new ResearchGroups)\n ' body = {'name': 'testgroup', 'description': 'Some Test Group'} request = self.factory.post(reverse('researchgroup-list'), json.dumps(body), content_type='application/json') request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'post': 'create'})(request) self.assertContains(response=response, text=, status_code=201)<|docstring|>Test Admin user can write ResearchGroup list (ie: create new ResearchGroups)<|endoftext|>
99d5e02d1d8a1afe18384219957d327f7e2b8fe65dbc1d83beeefab4807cdd44
def test_adminuser_read_researchgroup_detail(self): '\n Test Admin user can read an existing research group detail\n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') request = self.factory.get(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'retrieve'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text='', status_code=200)
Test Admin user can read an existing research group detail
api/radiam/api/tests/permissionstests/researchgrouppermissionstests.py
test_adminuser_read_researchgroup_detail
usask-rc/radiam
2
python
def test_adminuser_read_researchgroup_detail(self): '\n \n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') request = self.factory.get(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'retrieve'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=200)
def test_adminuser_read_researchgroup_detail(self): '\n \n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') request = self.factory.get(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'retrieve'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=200)<|docstring|>Test Admin user can read an existing research group detail<|endoftext|>
d16c2720c4aa6b6012b02d42441c5ca97308429e3160377f854047e3c6e88c61
def test_adminuser_write_researchgroup_detail(self): '\n Test Adminuser can update an existing research group detail\n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') body = {'description': 'updated description'} request = self.factory.patch(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'patch': 'partial_update'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text='', status_code=200)
Test Adminuser can update an existing research group detail
api/radiam/api/tests/permissionstests/researchgrouppermissionstests.py
test_adminuser_write_researchgroup_detail
usask-rc/radiam
2
python
def test_adminuser_write_researchgroup_detail(self): '\n \n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') body = {'description': 'updated description'} request = self.factory.patch(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'patch': 'partial_update'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=200)
def test_adminuser_write_researchgroup_detail(self): '\n \n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') body = {'description': 'updated description'} request = self.factory.patch(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'patch': 'partial_update'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=200)<|docstring|>Test Adminuser can update an existing research group detail<|endoftext|>
9d861154bf5bd473a2fc2b7201daa447d8c2b44caec340c3ae2caebbf295d7f3
def test_adminuser_cannot_write_researchgroup_detail(self): '\n Test Adminuser for one group cannot update an existing research\n group detail for a group they have only member access to.\n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 2') body = {'description': 'updated description'} request = self.factory.patch(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'patch': 'partial_update'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text='', status_code=403)
Test Adminuser for one group cannot update an existing research group detail for a group they have only member access to.
api/radiam/api/tests/permissionstests/researchgrouppermissionstests.py
test_adminuser_cannot_write_researchgroup_detail
usask-rc/radiam
2
python
def test_adminuser_cannot_write_researchgroup_detail(self): '\n Test Adminuser for one group cannot update an existing research\n group detail for a group they have only member access to.\n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 2') body = {'description': 'updated description'} request = self.factory.patch(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'patch': 'partial_update'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=403)
def test_adminuser_cannot_write_researchgroup_detail(self): '\n Test Adminuser for one group cannot update an existing research\n group detail for a group they have only member access to.\n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 2') body = {'description': 'updated description'} request = self.factory.patch(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'patch': 'partial_update'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=403)<|docstring|>Test Adminuser for one group cannot update an existing research group detail for a group they have only member access to.<|endoftext|>
5022edba73056600c9241123e40804f85801d8d3133b0732c1fc01a8b1600b63
def test_manageruser_read_researchgroup_list(self): '\n Test Manager user can read ResearchGroup list\n ' user_groups = self.user.get_groups() request = self.factory.get(reverse('researchgroup-list')) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'list'})(request) self.assertContains(response=response, text='', status_code=200) self.assertEquals(response.data['count'], user_groups.count())
Test Manager user can read ResearchGroup list
api/radiam/api/tests/permissionstests/researchgrouppermissionstests.py
test_manageruser_read_researchgroup_list
usask-rc/radiam
2
python
def test_manageruser_read_researchgroup_list(self): '\n \n ' user_groups = self.user.get_groups() request = self.factory.get(reverse('researchgroup-list')) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'list'})(request) self.assertContains(response=response, text=, status_code=200) self.assertEquals(response.data['count'], user_groups.count())
def test_manageruser_read_researchgroup_list(self): '\n \n ' user_groups = self.user.get_groups() request = self.factory.get(reverse('researchgroup-list')) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'list'})(request) self.assertContains(response=response, text=, status_code=200) self.assertEquals(response.data['count'], user_groups.count())<|docstring|>Test Manager user can read ResearchGroup list<|endoftext|>
869f3b74a5f8c4d8067c22f342bd100fe927ed281a3e229c3ee9399122031c0f
def test_manageruser_write_researchgroup_list(self): '\n Test Manager user can write ResearchGroup list\n (ie: create new ResearchGroups)\n ' body = {'name': 'testgroup', 'description': 'test group description'} request = self.factory.post(reverse('researchgroup-list'), json.dumps(body), content_type='application/json') request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'post': 'create'})(request) self.assertContains(response=response, text='', status_code=403)
Test Manager user can write ResearchGroup list (ie: create new ResearchGroups)
api/radiam/api/tests/permissionstests/researchgrouppermissionstests.py
test_manageruser_write_researchgroup_list
usask-rc/radiam
2
python
def test_manageruser_write_researchgroup_list(self): '\n Test Manager user can write ResearchGroup list\n (ie: create new ResearchGroups)\n ' body = {'name': 'testgroup', 'description': 'test group description'} request = self.factory.post(reverse('researchgroup-list'), json.dumps(body), content_type='application/json') request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'post': 'create'})(request) self.assertContains(response=response, text=, status_code=403)
def test_manageruser_write_researchgroup_list(self): '\n Test Manager user can write ResearchGroup list\n (ie: create new ResearchGroups)\n ' body = {'name': 'testgroup', 'description': 'test group description'} request = self.factory.post(reverse('researchgroup-list'), json.dumps(body), content_type='application/json') request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'post': 'create'})(request) self.assertContains(response=response, text=, status_code=403)<|docstring|>Test Manager user can write ResearchGroup list (ie: create new ResearchGroups)<|endoftext|>
defb87ce0f00df04434e2c7ca856c7aadddcff2953a60ab69e6e3798caa6b551
def test_manageruser_read_researchgroup_detail(self): '\n Test Manager user can read an existing research group\n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') request = self.factory.get(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'retrieve'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text='', status_code=200)
Test Manager user can read an existing research group
api/radiam/api/tests/permissionstests/researchgrouppermissionstests.py
test_manageruser_read_researchgroup_detail
usask-rc/radiam
2
python
def test_manageruser_read_researchgroup_detail(self): '\n \n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') request = self.factory.get(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'retrieve'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=200)
def test_manageruser_read_researchgroup_detail(self): '\n \n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') request = self.factory.get(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'retrieve'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=200)<|docstring|>Test Manager user can read an existing research group<|endoftext|>
c9732a68454652897c7fb922807d6cef1b94a7df7754c4d855fff62ad97700e9
def test_manageruser_write_researchgroup_detail_denied(self): '\n Test Manager user cannot update an existing research group\n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') body = {'description': 'updated description'} request = self.factory.patch(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'patch': 'partial_update'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text='', status_code=403)
Test Manager user cannot update an existing research group
api/radiam/api/tests/permissionstests/researchgrouppermissionstests.py
test_manageruser_write_researchgroup_detail_denied
usask-rc/radiam
2
python
def test_manageruser_write_researchgroup_detail_denied(self): '\n \n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') body = {'description': 'updated description'} request = self.factory.patch(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'patch': 'partial_update'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=403)
def test_manageruser_write_researchgroup_detail_denied(self): '\n \n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') body = {'description': 'updated description'} request = self.factory.patch(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'patch': 'partial_update'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=403)<|docstring|>Test Manager user cannot update an existing research group<|endoftext|>
e09c44477c3713a76e1a155ec9d62919ee2ecb93d3cb1f51a0ae98b6320aff04
def test_memberuser_read_researchgroup_list(self): '\n Test Member user can read ResearchGroup list\n ' user_groups = self.user.get_groups() request = self.factory.get(reverse('researchgroup-list')) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'list'})(request) self.assertContains(response=response, text='', status_code=200) self.assertEquals(response.data['count'], user_groups.count())
Test Member user can read ResearchGroup list
api/radiam/api/tests/permissionstests/researchgrouppermissionstests.py
test_memberuser_read_researchgroup_list
usask-rc/radiam
2
python
def test_memberuser_read_researchgroup_list(self): '\n \n ' user_groups = self.user.get_groups() request = self.factory.get(reverse('researchgroup-list')) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'list'})(request) self.assertContains(response=response, text=, status_code=200) self.assertEquals(response.data['count'], user_groups.count())
def test_memberuser_read_researchgroup_list(self): '\n \n ' user_groups = self.user.get_groups() request = self.factory.get(reverse('researchgroup-list')) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'list'})(request) self.assertContains(response=response, text=, status_code=200) self.assertEquals(response.data['count'], user_groups.count())<|docstring|>Test Member user can read ResearchGroup list<|endoftext|>
12c41e7a70ddfd56d18dd8afde2c5641863bfa5e5b586916e6b757a497531818
def test_memberuser_write_researchgroup_list_denied(self): '\n Test Member user cannot write ResearchGroup list\n (ie: create new ResearchGroups)\n ' body = {'name': 'testgroup', 'description': 'test group description'} request = self.factory.post(reverse('researchgroup-list'), json.dumps(body), content_type='application/json') request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'post': 'create'})(request) self.assertContains(response=response, text='', status_code=403)
Test Member user cannot write ResearchGroup list (ie: create new ResearchGroups)
api/radiam/api/tests/permissionstests/researchgrouppermissionstests.py
test_memberuser_write_researchgroup_list_denied
usask-rc/radiam
2
python
def test_memberuser_write_researchgroup_list_denied(self): '\n Test Member user cannot write ResearchGroup list\n (ie: create new ResearchGroups)\n ' body = {'name': 'testgroup', 'description': 'test group description'} request = self.factory.post(reverse('researchgroup-list'), json.dumps(body), content_type='application/json') request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'post': 'create'})(request) self.assertContains(response=response, text=, status_code=403)
def test_memberuser_write_researchgroup_list_denied(self): '\n Test Member user cannot write ResearchGroup list\n (ie: create new ResearchGroups)\n ' body = {'name': 'testgroup', 'description': 'test group description'} request = self.factory.post(reverse('researchgroup-list'), json.dumps(body), content_type='application/json') request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'post': 'create'})(request) self.assertContains(response=response, text=, status_code=403)<|docstring|>Test Member user cannot write ResearchGroup list (ie: create new ResearchGroups)<|endoftext|>
5f62bc5be883fd288f863d20b86528570d6ffe9de1a1c0c314b8b6d9716c4405
def test_memberuser_read_researchgroup_detail(self): '\n Test Member user can read an existing research group\n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') request = self.factory.get(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'retrieve'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text='', status_code=200)
Test Member user can read an existing research group
api/radiam/api/tests/permissionstests/researchgrouppermissionstests.py
test_memberuser_read_researchgroup_detail
usask-rc/radiam
2
python
def test_memberuser_read_researchgroup_detail(self): '\n \n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') request = self.factory.get(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'retrieve'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=200)
def test_memberuser_read_researchgroup_detail(self): '\n \n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') request = self.factory.get(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'retrieve'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=200)<|docstring|>Test Member user can read an existing research group<|endoftext|>
cc27887b6f335af7bfac70a04fc658831edba6b410cce6dd701bbb95a63dc2b9
def test_memberuser_read_nonmember_researchgroup_detail_denied(self): "\n Test Member user cannot read an existing research group they don't have access to\n " detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 2') request = self.factory.get(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'retrieve'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text='', status_code=404)
Test Member user cannot read an existing research group they don't have access to
api/radiam/api/tests/permissionstests/researchgrouppermissionstests.py
test_memberuser_read_nonmember_researchgroup_detail_denied
usask-rc/radiam
2
python
def test_memberuser_read_nonmember_researchgroup_detail_denied(self): "\n \n " detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 2') request = self.factory.get(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'retrieve'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=404)
def test_memberuser_read_nonmember_researchgroup_detail_denied(self): "\n \n " detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 2') request = self.factory.get(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'get': 'retrieve'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=404)<|docstring|>Test Member user cannot read an existing research group they don't have access to<|endoftext|>
8ea1f5fbb208551ebffc7d765729a2e6c8738a510c94ed3444e345e2f8dec8e6
def test_memberuser_write_researchgroup_detail_denied(self): '\n Test Memberuser cannot update an existing research group\n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') body = {'description': 'updated description'} request = self.factory.patch(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'patch': 'partial_update'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text='', status_code=403)
Test Memberuser cannot update an existing research group
api/radiam/api/tests/permissionstests/researchgrouppermissionstests.py
test_memberuser_write_researchgroup_detail_denied
usask-rc/radiam
2
python
def test_memberuser_write_researchgroup_detail_denied(self): '\n \n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') body = {'description': 'updated description'} request = self.factory.patch(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'patch': 'partial_update'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=403)
def test_memberuser_write_researchgroup_detail_denied(self): '\n \n ' detail_researchgroup = ResearchGroup.objects.get(name='Test Research Group 1') body = {'description': 'updated description'} request = self.factory.patch(reverse('researchgroup-detail', args=[detail_researchgroup.id])) request.user = self.user force_authenticate(request, user=request.user) response = ResearchGroupViewSet.as_view({'patch': 'partial_update'})(request, pk=detail_researchgroup.id) self.assertContains(response=response, text=, status_code=403)<|docstring|>Test Memberuser cannot update an existing research group<|endoftext|>
7784ea31740bad50efbed9ef7bb43c6ef21abfba9e03255f2db13893ee59cb44
def read_credits(self, path, separator=','): 'loads credits in a dict with one key per episode' credits = np.loadtxt(path, delimiter=separator, dtype=str) credits = {episode[0]: np.array(episode[1:], dtype=int) for episode in credits} return credits
loads credits in a dict with one key per episode
Plumcot/__init__.py
read_credits
hbredin/pyannote-db-plumcot
2
python
def read_credits(self, path, separator=','): credits = np.loadtxt(path, delimiter=separator, dtype=str) credits = {episode[0]: np.array(episode[1:], dtype=int) for episode in credits} return credits
def read_credits(self, path, separator=','): credits = np.loadtxt(path, delimiter=separator, dtype=str) credits = {episode[0]: np.array(episode[1:], dtype=int) for episode in credits} return credits<|docstring|>loads credits in a dict with one key per episode<|endoftext|>
fe78d562792284d38bf68cab5324414566e80b85340e9286674a0e08cd83a9eb
def get_characters(self, id_series, season_number=None, episode_number=None, field='character_uri'): "Get IMDB character's names list.\n\n Parameters\n ----------\n id_series : `str`\n Id of the series.\n season_number : `str`\n The desired season number. If None, all seasons are processed.\n episode_number : `str`\n The desired episodeNumber. If None, all episodes are processed.\n field : `str`, optional\n one of self.fields\n Defaults to character_uri\n\n Returns\n -------\n namesDict : `dict`\n Dictionary with episodeId as key and list of IMDB names as value.\n " ep_name = id_series if season_number: ep_name += f'.Season{season_number}' if episode_number: ep_name += f'.Episode{episode_number}' parent = Path(__file__).parent credits_file = (parent / f'data/{id_series}/credits.txt') characters_file = (parent / f'data/{id_series}/characters.txt') characters_list_credits = [] with open(credits_file, mode='r', encoding='utf8') as f: for line in f: line_split = line.split(',') if (ep_name in line_split[0]): characters_list_credits.append(line_split) characters_list = [] column = self.fields[field] with open(characters_file, mode='r', encoding='utf8') as f: for line in f: characters_list.append(line.split(',')[column]) characters_dict = {} for episode in characters_list_credits: episode_name = episode[0] characters_name_list = [] for (id_character, character) in enumerate(episode[1:]): if int(character): characters_name_list.append(characters_list[id_character]) characters_dict[episode_name] = characters_name_list return characters_dict
Get IMDB character's names list. Parameters ---------- id_series : `str` Id of the series. season_number : `str` The desired season number. If None, all seasons are processed. episode_number : `str` The desired episodeNumber. If None, all episodes are processed. field : `str`, optional one of self.fields Defaults to character_uri Returns ------- namesDict : `dict` Dictionary with episodeId as key and list of IMDB names as value.
Plumcot/__init__.py
get_characters
hbredin/pyannote-db-plumcot
2
python
def get_characters(self, id_series, season_number=None, episode_number=None, field='character_uri'): "Get IMDB character's names list.\n\n Parameters\n ----------\n id_series : `str`\n Id of the series.\n season_number : `str`\n The desired season number. If None, all seasons are processed.\n episode_number : `str`\n The desired episodeNumber. If None, all episodes are processed.\n field : `str`, optional\n one of self.fields\n Defaults to character_uri\n\n Returns\n -------\n namesDict : `dict`\n Dictionary with episodeId as key and list of IMDB names as value.\n " ep_name = id_series if season_number: ep_name += f'.Season{season_number}' if episode_number: ep_name += f'.Episode{episode_number}' parent = Path(__file__).parent credits_file = (parent / f'data/{id_series}/credits.txt') characters_file = (parent / f'data/{id_series}/characters.txt') characters_list_credits = [] with open(credits_file, mode='r', encoding='utf8') as f: for line in f: line_split = line.split(',') if (ep_name in line_split[0]): characters_list_credits.append(line_split) characters_list = [] column = self.fields[field] with open(characters_file, mode='r', encoding='utf8') as f: for line in f: characters_list.append(line.split(',')[column]) characters_dict = {} for episode in characters_list_credits: episode_name = episode[0] characters_name_list = [] for (id_character, character) in enumerate(episode[1:]): if int(character): characters_name_list.append(characters_list[id_character]) characters_dict[episode_name] = characters_name_list return characters_dict
def get_characters(self, id_series, season_number=None, episode_number=None, field='character_uri'): "Get IMDB character's names list.\n\n Parameters\n ----------\n id_series : `str`\n Id of the series.\n season_number : `str`\n The desired season number. If None, all seasons are processed.\n episode_number : `str`\n The desired episodeNumber. If None, all episodes are processed.\n field : `str`, optional\n one of self.fields\n Defaults to character_uri\n\n Returns\n -------\n namesDict : `dict`\n Dictionary with episodeId as key and list of IMDB names as value.\n " ep_name = id_series if season_number: ep_name += f'.Season{season_number}' if episode_number: ep_name += f'.Episode{episode_number}' parent = Path(__file__).parent credits_file = (parent / f'data/{id_series}/credits.txt') characters_file = (parent / f'data/{id_series}/characters.txt') characters_list_credits = [] with open(credits_file, mode='r', encoding='utf8') as f: for line in f: line_split = line.split(',') if (ep_name in line_split[0]): characters_list_credits.append(line_split) characters_list = [] column = self.fields[field] with open(characters_file, mode='r', encoding='utf8') as f: for line in f: characters_list.append(line.split(',')[column]) characters_dict = {} for episode in characters_list_credits: episode_name = episode[0] characters_name_list = [] for (id_character, character) in enumerate(episode[1:]): if int(character): characters_name_list.append(characters_list[id_character]) characters_dict[episode_name] = characters_name_list return characters_dict<|docstring|>Get IMDB character's names list. Parameters ---------- id_series : `str` Id of the series. season_number : `str` The desired season number. If None, all seasons are processed. episode_number : `str` The desired episodeNumber. If None, all episodes are processed. field : `str`, optional one of self.fields Defaults to character_uri Returns ------- namesDict : `dict` Dictionary with episodeId as key and list of IMDB names as value.<|endoftext|>
7cffae361dc1b733b197806c535c8bb3f8793fce3e9ea6497ca0aae37e844cfb
def get_transcript_characters(self, id_series, season_number=None, episode_number=None, extension='.temp'): "Get transcripts character's names list from transcripts files.\n\n Parameters\n ----------\n id_series : `str`\n Id of the series.\n season_number : `str`\n The desired season number. If None, all seasons are processed.\n episode_number : `str`\n The desired episodeNumber. If None, all episodes are processed.\n extension : `str`, optional\n extension of the transcripts files, defaults to '.temp'\n\n Returns\n -------\n namesDict : `dict`\n Dictionnary with episodeId as key and dictionnary as value with\n transcripts as key and number of speech turns as value\n " ep_template = id_series if season_number: ep_template += f'.Season{season_number}' if episode_number: ep_template += f'.Episode{episode_number}' parent = Path(__file__).parent transcripts = glob.glob(f'{parent}/data/{id_series}/transcripts/{ep_template}*{extension}') characters_dict = {} for file in transcripts: with open(file, mode='r', encoding='utf8') as ep_file: characters = {} for line in ep_file: if ((line == '') or line.isspace()): continue charac = line.split()[0] if self.merge_next_token(charac): charac += line.split()[1] if (charac not in characters): characters[charac] = 1 else: characters[charac] += 1 (ep_name, _) = os.path.splitext(os.path.split(file)[1]) characters_dict[ep_name] = characters return characters_dict
Get transcripts character's names list from transcripts files. Parameters ---------- id_series : `str` Id of the series. season_number : `str` The desired season number. If None, all seasons are processed. episode_number : `str` The desired episodeNumber. If None, all episodes are processed. extension : `str`, optional extension of the transcripts files, defaults to '.temp' Returns ------- namesDict : `dict` Dictionnary with episodeId as key and dictionnary as value with transcripts as key and number of speech turns as value
Plumcot/__init__.py
get_transcript_characters
hbredin/pyannote-db-plumcot
2
python
def get_transcript_characters(self, id_series, season_number=None, episode_number=None, extension='.temp'): "Get transcripts character's names list from transcripts files.\n\n Parameters\n ----------\n id_series : `str`\n Id of the series.\n season_number : `str`\n The desired season number. If None, all seasons are processed.\n episode_number : `str`\n The desired episodeNumber. If None, all episodes are processed.\n extension : `str`, optional\n extension of the transcripts files, defaults to '.temp'\n\n Returns\n -------\n namesDict : `dict`\n Dictionnary with episodeId as key and dictionnary as value with\n transcripts as key and number of speech turns as value\n " ep_template = id_series if season_number: ep_template += f'.Season{season_number}' if episode_number: ep_template += f'.Episode{episode_number}' parent = Path(__file__).parent transcripts = glob.glob(f'{parent}/data/{id_series}/transcripts/{ep_template}*{extension}') characters_dict = {} for file in transcripts: with open(file, mode='r', encoding='utf8') as ep_file: characters = {} for line in ep_file: if ((line == ) or line.isspace()): continue charac = line.split()[0] if self.merge_next_token(charac): charac += line.split()[1] if (charac not in characters): characters[charac] = 1 else: characters[charac] += 1 (ep_name, _) = os.path.splitext(os.path.split(file)[1]) characters_dict[ep_name] = characters return characters_dict
def get_transcript_characters(self, id_series, season_number=None, episode_number=None, extension='.temp'): "Get transcripts character's names list from transcripts files.\n\n Parameters\n ----------\n id_series : `str`\n Id of the series.\n season_number : `str`\n The desired season number. If None, all seasons are processed.\n episode_number : `str`\n The desired episodeNumber. If None, all episodes are processed.\n extension : `str`, optional\n extension of the transcripts files, defaults to '.temp'\n\n Returns\n -------\n namesDict : `dict`\n Dictionnary with episodeId as key and dictionnary as value with\n transcripts as key and number of speech turns as value\n " ep_template = id_series if season_number: ep_template += f'.Season{season_number}' if episode_number: ep_template += f'.Episode{episode_number}' parent = Path(__file__).parent transcripts = glob.glob(f'{parent}/data/{id_series}/transcripts/{ep_template}*{extension}') characters_dict = {} for file in transcripts: with open(file, mode='r', encoding='utf8') as ep_file: characters = {} for line in ep_file: if ((line == ) or line.isspace()): continue charac = line.split()[0] if self.merge_next_token(charac): charac += line.split()[1] if (charac not in characters): characters[charac] = 1 else: characters[charac] += 1 (ep_name, _) = os.path.splitext(os.path.split(file)[1]) characters_dict[ep_name] = characters return characters_dict<|docstring|>Get transcripts character's names list from transcripts files. Parameters ---------- id_series : `str` Id of the series. season_number : `str` The desired season number. If None, all seasons are processed. episode_number : `str` The desired episodeNumber. If None, all episodes are processed. extension : `str`, optional extension of the transcripts files, defaults to '.temp' Returns ------- namesDict : `dict` Dictionnary with episodeId as key and dictionnary as value with transcripts as key and number of speech turns as value<|endoftext|>
44f500994f09fd4e9b79c1b1c7b0dbc8073c9758c6703cde6cfb8ecfc64ee150
def save_normalized_names(self, id_series, id_ep, dic_names): 'Saves new transcripts files as .txt with normalized names.\n\n Parameters\n ----------\n id_series : `str`\n Id of the series.\n id_ep : `str`\n Id of the episode.\n dic_names : `dict`\n Dictionnary with matching names (transcript -> normalized).\n ' parent = Path(__file__).parent trans_folder = f'{parent}/data/{id_series}/transcripts/' file_text = '' with open(((trans_folder + id_ep) + '.temp'), mode='r', encoding='utf8') as ep_file: for line in ep_file: if ((line == '') or line.isspace()): continue line_split = line.split() if self.merge_next_token(line_split[0]): line_split[0] += line_split[1] line_split.pop(1) line_split[0] = dic_names[line_split[0]] file_text += (' '.join(line_split) + '\n') with open(((trans_folder + id_ep) + '.txt'), mode='w', encoding='utf8') as ep_file: ep_file.write(file_text)
Saves new transcripts files as .txt with normalized names. Parameters ---------- id_series : `str` Id of the series. id_ep : `str` Id of the episode. dic_names : `dict` Dictionnary with matching names (transcript -> normalized).
Plumcot/__init__.py
save_normalized_names
hbredin/pyannote-db-plumcot
2
python
def save_normalized_names(self, id_series, id_ep, dic_names): 'Saves new transcripts files as .txt with normalized names.\n\n Parameters\n ----------\n id_series : `str`\n Id of the series.\n id_ep : `str`\n Id of the episode.\n dic_names : `dict`\n Dictionnary with matching names (transcript -> normalized).\n ' parent = Path(__file__).parent trans_folder = f'{parent}/data/{id_series}/transcripts/' file_text = with open(((trans_folder + id_ep) + '.temp'), mode='r', encoding='utf8') as ep_file: for line in ep_file: if ((line == ) or line.isspace()): continue line_split = line.split() if self.merge_next_token(line_split[0]): line_split[0] += line_split[1] line_split.pop(1) line_split[0] = dic_names[line_split[0]] file_text += (' '.join(line_split) + '\n') with open(((trans_folder + id_ep) + '.txt'), mode='w', encoding='utf8') as ep_file: ep_file.write(file_text)
def save_normalized_names(self, id_series, id_ep, dic_names): 'Saves new transcripts files as .txt with normalized names.\n\n Parameters\n ----------\n id_series : `str`\n Id of the series.\n id_ep : `str`\n Id of the episode.\n dic_names : `dict`\n Dictionnary with matching names (transcript -> normalized).\n ' parent = Path(__file__).parent trans_folder = f'{parent}/data/{id_series}/transcripts/' file_text = with open(((trans_folder + id_ep) + '.temp'), mode='r', encoding='utf8') as ep_file: for line in ep_file: if ((line == ) or line.isspace()): continue line_split = line.split() if self.merge_next_token(line_split[0]): line_split[0] += line_split[1] line_split.pop(1) line_split[0] = dic_names[line_split[0]] file_text += (' '.join(line_split) + '\n') with open(((trans_folder + id_ep) + '.txt'), mode='w', encoding='utf8') as ep_file: ep_file.write(file_text)<|docstring|>Saves new transcripts files as .txt with normalized names. Parameters ---------- id_series : `str` Id of the series. id_ep : `str` Id of the episode. dic_names : `dict` Dictionnary with matching names (transcript -> normalized).<|endoftext|>
5addfef974bd0cd3e9932f5afcd1eb9f09e7becc719d326c4c267521132a157d
def combine_metrics(step_metrics): 'Given a list of metric dicts, combine to a single summary metrics dict.\n\n Args:\n step_metrics: A dict with (metric name, metric value) items. Contains summed\n metrics and the corresponding denominator (the number of next-token\n prediction instances). Each metric value have at least one dimension.\n\n Returns:\n A dict with (metric name, metric value) items containing combined metrics.\n ' metrics_all = common_utils.get_metrics(step_metrics) lr = None if ('learning_rate' in metrics_all): lr = metrics_all.pop('learning_rate').mean() metrics_sums = jax.tree_map(jnp.sum, metrics_all) denominator = metrics_sums.pop('denominator') summary = jax.tree_map((lambda x: (x / denominator)), metrics_sums) if (lr is not None): summary['learning_rate'] = lr if ('loss' in summary): summary['perplexity'] = jnp.clip(jnp.exp(summary['loss']), a_max=10000.0) return summary
Given a list of metric dicts, combine to a single summary metrics dict. Args: step_metrics: A dict with (metric name, metric value) items. Contains summed metrics and the corresponding denominator (the number of next-token prediction instances). Each metric value have at least one dimension. Returns: A dict with (metric name, metric value) items containing combined metrics.
protein_lm/evaluation.py
combine_metrics
wy-go/google-research
23,901
python
def combine_metrics(step_metrics): 'Given a list of metric dicts, combine to a single summary metrics dict.\n\n Args:\n step_metrics: A dict with (metric name, metric value) items. Contains summed\n metrics and the corresponding denominator (the number of next-token\n prediction instances). Each metric value have at least one dimension.\n\n Returns:\n A dict with (metric name, metric value) items containing combined metrics.\n ' metrics_all = common_utils.get_metrics(step_metrics) lr = None if ('learning_rate' in metrics_all): lr = metrics_all.pop('learning_rate').mean() metrics_sums = jax.tree_map(jnp.sum, metrics_all) denominator = metrics_sums.pop('denominator') summary = jax.tree_map((lambda x: (x / denominator)), metrics_sums) if (lr is not None): summary['learning_rate'] = lr if ('loss' in summary): summary['perplexity'] = jnp.clip(jnp.exp(summary['loss']), a_max=10000.0) return summary
def combine_metrics(step_metrics): 'Given a list of metric dicts, combine to a single summary metrics dict.\n\n Args:\n step_metrics: A dict with (metric name, metric value) items. Contains summed\n metrics and the corresponding denominator (the number of next-token\n prediction instances). Each metric value have at least one dimension.\n\n Returns:\n A dict with (metric name, metric value) items containing combined metrics.\n ' metrics_all = common_utils.get_metrics(step_metrics) lr = None if ('learning_rate' in metrics_all): lr = metrics_all.pop('learning_rate').mean() metrics_sums = jax.tree_map(jnp.sum, metrics_all) denominator = metrics_sums.pop('denominator') summary = jax.tree_map((lambda x: (x / denominator)), metrics_sums) if (lr is not None): summary['learning_rate'] = lr if ('loss' in summary): summary['perplexity'] = jnp.clip(jnp.exp(summary['loss']), a_max=10000.0) return summary<|docstring|>Given a list of metric dicts, combine to a single summary metrics dict. Args: step_metrics: A dict with (metric name, metric value) items. Contains summed metrics and the corresponding denominator (the number of next-token prediction instances). Each metric value have at least one dimension. Returns: A dict with (metric name, metric value) items containing combined metrics.<|endoftext|>
f5eeda103350b4c2a9370c858b937f2e3bfe007b29feaa9adc9049540edaaff0
def evaluate(model, eval_ds, num_eval_steps=None): 'Evaluates model on eval_ds for num_eval_steps.\n\n Args:\n model: A model to use for evaluation. Must have an evaluate_batch() method.\n eval_ds: A tensorflow dataset containing the data to be used for evaluation.\n num_eval_steps: If given, evaluate for this many steps, otherwise use the\n entire dataset.\n\n Returns:\n A dictionary with (metric name, metric value) items.\n ' eval_metrics = [] eval_iter = iter(eval_ds) if (num_eval_steps is None): num_iter = itertools.repeat(1) else: num_iter = range(num_eval_steps) for (_, eval_batch) in zip(num_iter, eval_iter): eval_batch = np.asarray(eval_batch) metrics = model.evaluate_batch(eval_batch) eval_metrics.append(metrics) eval_summary = combine_metrics(eval_metrics) return eval_summary
Evaluates model on eval_ds for num_eval_steps. Args: model: A model to use for evaluation. Must have an evaluate_batch() method. eval_ds: A tensorflow dataset containing the data to be used for evaluation. num_eval_steps: If given, evaluate for this many steps, otherwise use the entire dataset. Returns: A dictionary with (metric name, metric value) items.
protein_lm/evaluation.py
evaluate
wy-go/google-research
23,901
python
def evaluate(model, eval_ds, num_eval_steps=None): 'Evaluates model on eval_ds for num_eval_steps.\n\n Args:\n model: A model to use for evaluation. Must have an evaluate_batch() method.\n eval_ds: A tensorflow dataset containing the data to be used for evaluation.\n num_eval_steps: If given, evaluate for this many steps, otherwise use the\n entire dataset.\n\n Returns:\n A dictionary with (metric name, metric value) items.\n ' eval_metrics = [] eval_iter = iter(eval_ds) if (num_eval_steps is None): num_iter = itertools.repeat(1) else: num_iter = range(num_eval_steps) for (_, eval_batch) in zip(num_iter, eval_iter): eval_batch = np.asarray(eval_batch) metrics = model.evaluate_batch(eval_batch) eval_metrics.append(metrics) eval_summary = combine_metrics(eval_metrics) return eval_summary
def evaluate(model, eval_ds, num_eval_steps=None): 'Evaluates model on eval_ds for num_eval_steps.\n\n Args:\n model: A model to use for evaluation. Must have an evaluate_batch() method.\n eval_ds: A tensorflow dataset containing the data to be used for evaluation.\n num_eval_steps: If given, evaluate for this many steps, otherwise use the\n entire dataset.\n\n Returns:\n A dictionary with (metric name, metric value) items.\n ' eval_metrics = [] eval_iter = iter(eval_ds) if (num_eval_steps is None): num_iter = itertools.repeat(1) else: num_iter = range(num_eval_steps) for (_, eval_batch) in zip(num_iter, eval_iter): eval_batch = np.asarray(eval_batch) metrics = model.evaluate_batch(eval_batch) eval_metrics.append(metrics) eval_summary = combine_metrics(eval_metrics) return eval_summary<|docstring|>Evaluates model on eval_ds for num_eval_steps. Args: model: A model to use for evaluation. Must have an evaluate_batch() method. eval_ds: A tensorflow dataset containing the data to be used for evaluation. num_eval_steps: If given, evaluate for this many steps, otherwise use the entire dataset. Returns: A dictionary with (metric name, metric value) items.<|endoftext|>
0609bbe964a83f7afcd8a663284af73f07983fa6a33d9931722671caae344cf4
def __init__(self, domain, train_ds, alpha=1.0): "Creates an instance of this class.\n\n # TODO(gandreea): It's unclear how to handle the length (EOS token). The\n # fact that the uniform baseline is reported as (perplexity=25,\n # accuracy=0.04) suggests that the EOS prediction step is not included.\n\n Args:\n domain: An instance of domains.Domain.\n train_ds: A tf.data.Dataset containing the data to be used for computing\n the empirical distribution.\n alpha: A float indicating the Laplace smoothing constant.\n " self._vocab_size = domain.vocab_size self._token_indices = [idx for idx in range(len(domain.vocab.tokens)) if ((idx != domain.vocab.bos) and (idx != domain.vocab.eos))] self._mask_token = domain.vocab.bos self._empirical_dist = np.zeros((len(self._token_indices),)) for batch in train_ds: batch = np.atleast_2d(batch) batch_one_hot = np.eye(self._vocab_size)[batch] batch_one_hot = np.take(batch_one_hot, self._token_indices, axis=(- 1)) self._empirical_dist += np.sum(np.sum(batch_one_hot, axis=0), axis=0) self._empirical_dist += alpha self._empirical_dist /= np.sum(self._empirical_dist)
Creates an instance of this class. # TODO(gandreea): It's unclear how to handle the length (EOS token). The # fact that the uniform baseline is reported as (perplexity=25, # accuracy=0.04) suggests that the EOS prediction step is not included. Args: domain: An instance of domains.Domain. train_ds: A tf.data.Dataset containing the data to be used for computing the empirical distribution. alpha: A float indicating the Laplace smoothing constant.
protein_lm/evaluation.py
__init__
wy-go/google-research
23,901
python
def __init__(self, domain, train_ds, alpha=1.0): "Creates an instance of this class.\n\n # TODO(gandreea): It's unclear how to handle the length (EOS token). The\n # fact that the uniform baseline is reported as (perplexity=25,\n # accuracy=0.04) suggests that the EOS prediction step is not included.\n\n Args:\n domain: An instance of domains.Domain.\n train_ds: A tf.data.Dataset containing the data to be used for computing\n the empirical distribution.\n alpha: A float indicating the Laplace smoothing constant.\n " self._vocab_size = domain.vocab_size self._token_indices = [idx for idx in range(len(domain.vocab.tokens)) if ((idx != domain.vocab.bos) and (idx != domain.vocab.eos))] self._mask_token = domain.vocab.bos self._empirical_dist = np.zeros((len(self._token_indices),)) for batch in train_ds: batch = np.atleast_2d(batch) batch_one_hot = np.eye(self._vocab_size)[batch] batch_one_hot = np.take(batch_one_hot, self._token_indices, axis=(- 1)) self._empirical_dist += np.sum(np.sum(batch_one_hot, axis=0), axis=0) self._empirical_dist += alpha self._empirical_dist /= np.sum(self._empirical_dist)
def __init__(self, domain, train_ds, alpha=1.0): "Creates an instance of this class.\n\n # TODO(gandreea): It's unclear how to handle the length (EOS token). The\n # fact that the uniform baseline is reported as (perplexity=25,\n # accuracy=0.04) suggests that the EOS prediction step is not included.\n\n Args:\n domain: An instance of domains.Domain.\n train_ds: A tf.data.Dataset containing the data to be used for computing\n the empirical distribution.\n alpha: A float indicating the Laplace smoothing constant.\n " self._vocab_size = domain.vocab_size self._token_indices = [idx for idx in range(len(domain.vocab.tokens)) if ((idx != domain.vocab.bos) and (idx != domain.vocab.eos))] self._mask_token = domain.vocab.bos self._empirical_dist = np.zeros((len(self._token_indices),)) for batch in train_ds: batch = np.atleast_2d(batch) batch_one_hot = np.eye(self._vocab_size)[batch] batch_one_hot = np.take(batch_one_hot, self._token_indices, axis=(- 1)) self._empirical_dist += np.sum(np.sum(batch_one_hot, axis=0), axis=0) self._empirical_dist += alpha self._empirical_dist /= np.sum(self._empirical_dist)<|docstring|>Creates an instance of this class. # TODO(gandreea): It's unclear how to handle the length (EOS token). The # fact that the uniform baseline is reported as (perplexity=25, # accuracy=0.04) suggests that the EOS prediction step is not included. Args: domain: An instance of domains.Domain. train_ds: A tf.data.Dataset containing the data to be used for computing the empirical distribution. alpha: A float indicating the Laplace smoothing constant.<|endoftext|>
c6784a40a5519da8089dafeca19111b4c15f974c78b55d3740ce8e5e1c8f7667
def evaluate_batch(self, batch): 'Computes all metrics on the given batch.' labels = np.atleast_2d(batch) logits = np.log(self._empirical_dist) logits = np.tile(logits, (list(labels.shape) + [1])) weights = np.where((labels != self._mask_token), 1, 0) metrics = utils.compute_metrics(logits, labels, weights) for (key, value) in metrics.items(): metrics[key] = jnp.atleast_1d(value) return metrics
Computes all metrics on the given batch.
protein_lm/evaluation.py
evaluate_batch
wy-go/google-research
23,901
python
def evaluate_batch(self, batch): labels = np.atleast_2d(batch) logits = np.log(self._empirical_dist) logits = np.tile(logits, (list(labels.shape) + [1])) weights = np.where((labels != self._mask_token), 1, 0) metrics = utils.compute_metrics(logits, labels, weights) for (key, value) in metrics.items(): metrics[key] = jnp.atleast_1d(value) return metrics
def evaluate_batch(self, batch): labels = np.atleast_2d(batch) logits = np.log(self._empirical_dist) logits = np.tile(logits, (list(labels.shape) + [1])) weights = np.where((labels != self._mask_token), 1, 0) metrics = utils.compute_metrics(logits, labels, weights) for (key, value) in metrics.items(): metrics[key] = jnp.atleast_1d(value) return metrics<|docstring|>Computes all metrics on the given batch.<|endoftext|>
878dce78c803ddf0846cfe73a483e2ad51652500eef1e121a0be35cef8c8aba7
@property def expired(self): '\n Checks if the auth token is expired or not\n\n :return: (Bool) True if expired, False if not\n ' return (self.expires_at < datetime.datetime.now())
Checks if the auth token is expired or not :return: (Bool) True if expired, False if not
pyspot/auth.py
expired
EdMan1022/PySpot
0
python
@property def expired(self): '\n Checks if the auth token is expired or not\n\n :return: (Bool) True if expired, False if not\n ' return (self.expires_at < datetime.datetime.now())
@property def expired(self): '\n Checks if the auth token is expired or not\n\n :return: (Bool) True if expired, False if not\n ' return (self.expires_at < datetime.datetime.now())<|docstring|>Checks if the auth token is expired or not :return: (Bool) True if expired, False if not<|endoftext|>
a8150e6b0c600044be9f221c0f6d77ddf4fa8e6bc52154443e4ec41895e769bd
def get_service(resource_group_name: Optional[str]=None, resource_name: Optional[str]=None, opts: Optional[pulumi.InvokeOptions]=None) -> AwaitableGetServiceResult: '\n The description of the service.\n API Version: 2021-01-11.\n\n\n :param str resource_group_name: The name of the resource group that contains the service instance.\n :param str resource_name: The name of the service instance.\n ' __args__ = dict() __args__['resourceGroupName'] = resource_group_name __args__['resourceName'] = resource_name if (opts is None): opts = pulumi.InvokeOptions() if (opts.version is None): opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-nextgen:healthcareapis:getService', __args__, opts=opts, typ=GetServiceResult).value return AwaitableGetServiceResult(etag=__ret__.etag, id=__ret__.id, identity=__ret__.identity, kind=__ret__.kind, location=__ret__.location, name=__ret__.name, properties=__ret__.properties, system_data=__ret__.system_data, tags=__ret__.tags, type=__ret__.type)
The description of the service. API Version: 2021-01-11. :param str resource_group_name: The name of the resource group that contains the service instance. :param str resource_name: The name of the service instance.
sdk/python/pulumi_azure_nextgen/healthcareapis/get_service.py
get_service
pulumi/pulumi-azure-nextgen
31
python
def get_service(resource_group_name: Optional[str]=None, resource_name: Optional[str]=None, opts: Optional[pulumi.InvokeOptions]=None) -> AwaitableGetServiceResult: '\n The description of the service.\n API Version: 2021-01-11.\n\n\n :param str resource_group_name: The name of the resource group that contains the service instance.\n :param str resource_name: The name of the service instance.\n ' __args__ = dict() __args__['resourceGroupName'] = resource_group_name __args__['resourceName'] = resource_name if (opts is None): opts = pulumi.InvokeOptions() if (opts.version is None): opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-nextgen:healthcareapis:getService', __args__, opts=opts, typ=GetServiceResult).value return AwaitableGetServiceResult(etag=__ret__.etag, id=__ret__.id, identity=__ret__.identity, kind=__ret__.kind, location=__ret__.location, name=__ret__.name, properties=__ret__.properties, system_data=__ret__.system_data, tags=__ret__.tags, type=__ret__.type)
def get_service(resource_group_name: Optional[str]=None, resource_name: Optional[str]=None, opts: Optional[pulumi.InvokeOptions]=None) -> AwaitableGetServiceResult: '\n The description of the service.\n API Version: 2021-01-11.\n\n\n :param str resource_group_name: The name of the resource group that contains the service instance.\n :param str resource_name: The name of the service instance.\n ' __args__ = dict() __args__['resourceGroupName'] = resource_group_name __args__['resourceName'] = resource_name if (opts is None): opts = pulumi.InvokeOptions() if (opts.version is None): opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-nextgen:healthcareapis:getService', __args__, opts=opts, typ=GetServiceResult).value return AwaitableGetServiceResult(etag=__ret__.etag, id=__ret__.id, identity=__ret__.identity, kind=__ret__.kind, location=__ret__.location, name=__ret__.name, properties=__ret__.properties, system_data=__ret__.system_data, tags=__ret__.tags, type=__ret__.type)<|docstring|>The description of the service. API Version: 2021-01-11. :param str resource_group_name: The name of the resource group that contains the service instance. :param str resource_name: The name of the service instance.<|endoftext|>
02d3f3889ff4d663cdd33afadfc48fe04fdc771babe6de8a313ff7982879eced
@property @pulumi.getter def etag(self) -> Optional[str]: '\n An etag associated with the resource, used for optimistic concurrency when editing it.\n ' return pulumi.get(self, 'etag')
An etag associated with the resource, used for optimistic concurrency when editing it.
sdk/python/pulumi_azure_nextgen/healthcareapis/get_service.py
etag
pulumi/pulumi-azure-nextgen
31
python
@property @pulumi.getter def etag(self) -> Optional[str]: '\n \n ' return pulumi.get(self, 'etag')
@property @pulumi.getter def etag(self) -> Optional[str]: '\n \n ' return pulumi.get(self, 'etag')<|docstring|>An etag associated with the resource, used for optimistic concurrency when editing it.<|endoftext|>
d96a38dacfbb736ce012102fcb340f2bf8606d3b360b799ebe05255a3065615a
@property @pulumi.getter def id(self) -> str: '\n The resource identifier.\n ' return pulumi.get(self, 'id')
The resource identifier.
sdk/python/pulumi_azure_nextgen/healthcareapis/get_service.py
id
pulumi/pulumi-azure-nextgen
31
python
@property @pulumi.getter def id(self) -> str: '\n \n ' return pulumi.get(self, 'id')
@property @pulumi.getter def id(self) -> str: '\n \n ' return pulumi.get(self, 'id')<|docstring|>The resource identifier.<|endoftext|>
b93011dda189fe20837a1f434ee3b9ea6e14b7868a2c6099475a8628eaa0e18d
@property @pulumi.getter def identity(self) -> Optional['outputs.ServicesResourceResponseIdentity']: '\n Setting indicating whether the service has a managed identity associated with it.\n ' return pulumi.get(self, 'identity')
Setting indicating whether the service has a managed identity associated with it.
sdk/python/pulumi_azure_nextgen/healthcareapis/get_service.py
identity
pulumi/pulumi-azure-nextgen
31
python
@property @pulumi.getter def identity(self) -> Optional['outputs.ServicesResourceResponseIdentity']: '\n \n ' return pulumi.get(self, 'identity')
@property @pulumi.getter def identity(self) -> Optional['outputs.ServicesResourceResponseIdentity']: '\n \n ' return pulumi.get(self, 'identity')<|docstring|>Setting indicating whether the service has a managed identity associated with it.<|endoftext|>
6dc7f43b0d865fa10c07ccb7ee8e14ba4ee0f063354cba03e0eba0710095ee1c
@property @pulumi.getter def kind(self) -> str: '\n The kind of the service.\n ' return pulumi.get(self, 'kind')
The kind of the service.
sdk/python/pulumi_azure_nextgen/healthcareapis/get_service.py
kind
pulumi/pulumi-azure-nextgen
31
python
@property @pulumi.getter def kind(self) -> str: '\n \n ' return pulumi.get(self, 'kind')
@property @pulumi.getter def kind(self) -> str: '\n \n ' return pulumi.get(self, 'kind')<|docstring|>The kind of the service.<|endoftext|>
165e462e7f94a0952e344c94a09fbaa4356a5f63c92501f42c132318dd11c52b
@property @pulumi.getter def location(self) -> str: '\n The resource location.\n ' return pulumi.get(self, 'location')
The resource location.
sdk/python/pulumi_azure_nextgen/healthcareapis/get_service.py
location
pulumi/pulumi-azure-nextgen
31
python
@property @pulumi.getter def location(self) -> str: '\n \n ' return pulumi.get(self, 'location')
@property @pulumi.getter def location(self) -> str: '\n \n ' return pulumi.get(self, 'location')<|docstring|>The resource location.<|endoftext|>
ca817b070e6ca361f1d82d0a6bc278287847b7e7c8c12f401bde345d617dc261
@property @pulumi.getter def name(self) -> str: '\n The resource name.\n ' return pulumi.get(self, 'name')
The resource name.
sdk/python/pulumi_azure_nextgen/healthcareapis/get_service.py
name
pulumi/pulumi-azure-nextgen
31
python
@property @pulumi.getter def name(self) -> str: '\n \n ' return pulumi.get(self, 'name')
@property @pulumi.getter def name(self) -> str: '\n \n ' return pulumi.get(self, 'name')<|docstring|>The resource name.<|endoftext|>
f1951f4d1c7ad2a50eb740dc5f0bc8cc38f7961652d95a2e36a7c92bca461313
@property @pulumi.getter def properties(self) -> 'outputs.ServicesPropertiesResponse': '\n The common properties of a service.\n ' return pulumi.get(self, 'properties')
The common properties of a service.
sdk/python/pulumi_azure_nextgen/healthcareapis/get_service.py
properties
pulumi/pulumi-azure-nextgen
31
python
@property @pulumi.getter def properties(self) -> 'outputs.ServicesPropertiesResponse': '\n \n ' return pulumi.get(self, 'properties')
@property @pulumi.getter def properties(self) -> 'outputs.ServicesPropertiesResponse': '\n \n ' return pulumi.get(self, 'properties')<|docstring|>The common properties of a service.<|endoftext|>
6a9512e3b36a04a382cb380fe5577050b432a8f40e365a73f4747eca6cb3aa28
@property @pulumi.getter(name='systemData') def system_data(self) -> 'outputs.SystemDataResponse': '\n Metadata pertaining to creation and last modification of the resource.\n ' return pulumi.get(self, 'system_data')
Metadata pertaining to creation and last modification of the resource.
sdk/python/pulumi_azure_nextgen/healthcareapis/get_service.py
system_data
pulumi/pulumi-azure-nextgen
31
python
@property @pulumi.getter(name='systemData') def system_data(self) -> 'outputs.SystemDataResponse': '\n \n ' return pulumi.get(self, 'system_data')
@property @pulumi.getter(name='systemData') def system_data(self) -> 'outputs.SystemDataResponse': '\n \n ' return pulumi.get(self, 'system_data')<|docstring|>Metadata pertaining to creation and last modification of the resource.<|endoftext|>
f03748afd5b1e300d8689ec13f85fdecbde93416427230bd6607e12689c9829e
@property @pulumi.getter def tags(self) -> Optional[Mapping[(str, str)]]: '\n The resource tags.\n ' return pulumi.get(self, 'tags')
The resource tags.
sdk/python/pulumi_azure_nextgen/healthcareapis/get_service.py
tags
pulumi/pulumi-azure-nextgen
31
python
@property @pulumi.getter def tags(self) -> Optional[Mapping[(str, str)]]: '\n \n ' return pulumi.get(self, 'tags')
@property @pulumi.getter def tags(self) -> Optional[Mapping[(str, str)]]: '\n \n ' return pulumi.get(self, 'tags')<|docstring|>The resource tags.<|endoftext|>
afb401c924551962ca5491309ce73ac1f3f95ccc17711e55f9a9030e93379198
@property @pulumi.getter def type(self) -> str: '\n The resource type.\n ' return pulumi.get(self, 'type')
The resource type.
sdk/python/pulumi_azure_nextgen/healthcareapis/get_service.py
type
pulumi/pulumi-azure-nextgen
31
python
@property @pulumi.getter def type(self) -> str: '\n \n ' return pulumi.get(self, 'type')
@property @pulumi.getter def type(self) -> str: '\n \n ' return pulumi.get(self, 'type')<|docstring|>The resource type.<|endoftext|>
c9c8b0bd2fddf0434f1ca237196ef03902ef5f70b3a3fc812eb8fc05021c892d
def touch_file(fname, mode=438, dir_fd=None, **kwargs): '\n Touch function taken from stackoverflow\n Link: https://stackoverflow.com/questions/1158076/implement-touch-using-python\n ' flags = (os.O_CREAT | os.O_APPEND) with os.fdopen(os.open(fname, flags=flags, mode=mode, dir_fd=dir_fd)) as f: os.utime((f.fileno() if (os.utime in os.supports_fd) else fname), dir_fd=(None if os.supports_fd else dir_fd), **kwargs)
Touch function taken from stackoverflow Link: https://stackoverflow.com/questions/1158076/implement-touch-using-python
python/glassfunc.py
touch_file
Kcjohnson/SCGP
16
python
def touch_file(fname, mode=438, dir_fd=None, **kwargs): '\n Touch function taken from stackoverflow\n Link: https://stackoverflow.com/questions/1158076/implement-touch-using-python\n ' flags = (os.O_CREAT | os.O_APPEND) with os.fdopen(os.open(fname, flags=flags, mode=mode, dir_fd=dir_fd)) as f: os.utime((f.fileno() if (os.utime in os.supports_fd) else fname), dir_fd=(None if os.supports_fd else dir_fd), **kwargs)
def touch_file(fname, mode=438, dir_fd=None, **kwargs): '\n Touch function taken from stackoverflow\n Link: https://stackoverflow.com/questions/1158076/implement-touch-using-python\n ' flags = (os.O_CREAT | os.O_APPEND) with os.fdopen(os.open(fname, flags=flags, mode=mode, dir_fd=dir_fd)) as f: os.utime((f.fileno() if (os.utime in os.supports_fd) else fname), dir_fd=(None if os.supports_fd else dir_fd), **kwargs)<|docstring|>Touch function taken from stackoverflow Link: https://stackoverflow.com/questions/1158076/implement-touch-using-python<|endoftext|>
30fff8ffabecf45bdec6312c1dd292df147164751120ff4cee21fe4a0efdf54f
def build_dict(seq, key): '\n Turn an unnamed list of dicts into a nammed list of dicts\n Taken from stackoverflow\n https://stackoverflow.com/questions/4391697/find-the-index-of-a-dict-within-a-list-by-matching-the-dicts-value\n ' return dict(((d[key], dict(d, index=index)) for (index, d) in enumerate(seq)))
Turn an unnamed list of dicts into a nammed list of dicts Taken from stackoverflow https://stackoverflow.com/questions/4391697/find-the-index-of-a-dict-within-a-list-by-matching-the-dicts-value
python/glassfunc.py
build_dict
Kcjohnson/SCGP
16
python
def build_dict(seq, key): '\n Turn an unnamed list of dicts into a nammed list of dicts\n Taken from stackoverflow\n https://stackoverflow.com/questions/4391697/find-the-index-of-a-dict-within-a-list-by-matching-the-dicts-value\n ' return dict(((d[key], dict(d, index=index)) for (index, d) in enumerate(seq)))
def build_dict(seq, key): '\n Turn an unnamed list of dicts into a nammed list of dicts\n Taken from stackoverflow\n https://stackoverflow.com/questions/4391697/find-the-index-of-a-dict-within-a-list-by-matching-the-dicts-value\n ' return dict(((d[key], dict(d, index=index)) for (index, d) in enumerate(seq)))<|docstring|>Turn an unnamed list of dicts into a nammed list of dicts Taken from stackoverflow https://stackoverflow.com/questions/4391697/find-the-index-of-a-dict-within-a-list-by-matching-the-dicts-value<|endoftext|>
5e7bf3dfafb4c8d1f6a200c6dfcbb84dbd00592fdb9a4632bfd23558d141d6ea
def dbconfig(filename, section): '\n Loads db connection settings in text file\n From http://www.postgresqltutorial.com/postgresql-python/connect/\n ' parser = ConfigParser() parser.read(filename) db = {} if parser.has_section(section): params = parser.items(section) for param in params: db[param[0]] = param[1] else: raise Exception('Section {0} not found in the {1} file'.format(section, filename)) return db
Loads db connection settings in text file From http://www.postgresqltutorial.com/postgresql-python/connect/
python/glassfunc.py
dbconfig
Kcjohnson/SCGP
16
python
def dbconfig(filename, section): '\n Loads db connection settings in text file\n From http://www.postgresqltutorial.com/postgresql-python/connect/\n ' parser = ConfigParser() parser.read(filename) db = {} if parser.has_section(section): params = parser.items(section) for param in params: db[param[0]] = param[1] else: raise Exception('Section {0} not found in the {1} file'.format(section, filename)) return db
def dbconfig(filename, section): '\n Loads db connection settings in text file\n From http://www.postgresqltutorial.com/postgresql-python/connect/\n ' parser = ConfigParser() parser.read(filename) db = {} if parser.has_section(section): params = parser.items(section) for param in params: db[param[0]] = param[1] else: raise Exception('Section {0} not found in the {1} file'.format(section, filename)) return db<|docstring|>Loads db connection settings in text file From http://www.postgresqltutorial.com/postgresql-python/connect/<|endoftext|>
57a147f222fe6b466be88d2ed8a659d691b28fd5c2b424ac40f3c5feaad0e394
def locate(pattern, root=os.curdir): '\n Locate all files matching supplied filename pattern in and below\n supplied root directory.\n Taken from: http://code.activestate.com/recipes/499305-locating-files-throughout-a-directory-tree/\n ' for (path, dirs, files) in os.walk(os.path.abspath(root)): for filename in fnmatch.filter(files, pattern): (yield os.path.join(path, filename))
Locate all files matching supplied filename pattern in and below supplied root directory. Taken from: http://code.activestate.com/recipes/499305-locating-files-throughout-a-directory-tree/
python/glassfunc.py
locate
Kcjohnson/SCGP
16
python
def locate(pattern, root=os.curdir): '\n Locate all files matching supplied filename pattern in and below\n supplied root directory.\n Taken from: http://code.activestate.com/recipes/499305-locating-files-throughout-a-directory-tree/\n ' for (path, dirs, files) in os.walk(os.path.abspath(root)): for filename in fnmatch.filter(files, pattern): (yield os.path.join(path, filename))
def locate(pattern, root=os.curdir): '\n Locate all files matching supplied filename pattern in and below\n supplied root directory.\n Taken from: http://code.activestate.com/recipes/499305-locating-files-throughout-a-directory-tree/\n ' for (path, dirs, files) in os.walk(os.path.abspath(root)): for filename in fnmatch.filter(files, pattern): (yield os.path.join(path, filename))<|docstring|>Locate all files matching supplied filename pattern in and below supplied root directory. Taken from: http://code.activestate.com/recipes/499305-locating-files-throughout-a-directory-tree/<|endoftext|>
47c947d4992acf7f8c6dd1a7a9b1f9f9deb02d996624e667c5f1ca20edf0e27a
def test_dist_fetch_build_egg(tmpdir): '\n Check multiple calls to `Distribution.fetch_build_egg` work as expected.\n ' index = tmpdir.mkdir('index') index_url = urljoin('file://', pathname2url(str(index))) def sdist_with_index(distname, version): dist_dir = index.mkdir(distname) dist_sdist = ('%s-%s.tar.gz' % (distname, version)) make_nspkg_sdist(str(dist_dir.join(dist_sdist)), distname, version) with dist_dir.join('index.html').open('w') as fp: fp.write(DALS('\n <!DOCTYPE html><html><body>\n <a href="{dist_sdist}" rel="internal">{dist_sdist}</a><br/>\n </body></html>\n ').format(dist_sdist=dist_sdist)) sdist_with_index('barbazquux', '3.2.0') sdist_with_index('barbazquux-runner', '2.11.1') with tmpdir.join('setup.cfg').open('w') as fp: fp.write(DALS('\n [easy_install]\n index_url = {index_url}\n ').format(index_url=index_url)) reqs = '\n barbazquux-runner\n barbazquux\n '.split() with tmpdir.as_cwd(): dist = Distribution() dist.parse_config_files() resolved_dists = [dist.fetch_build_egg(r) for r in reqs] assert ([dist.key for dist in resolved_dists if dist] == reqs)
Check multiple calls to `Distribution.fetch_build_egg` work as expected.
setuptools/tests/test_dist.py
test_dist_fetch_build_egg
oss-qm/python-setuptools
2
python
def test_dist_fetch_build_egg(tmpdir): '\n \n ' index = tmpdir.mkdir('index') index_url = urljoin('file://', pathname2url(str(index))) def sdist_with_index(distname, version): dist_dir = index.mkdir(distname) dist_sdist = ('%s-%s.tar.gz' % (distname, version)) make_nspkg_sdist(str(dist_dir.join(dist_sdist)), distname, version) with dist_dir.join('index.html').open('w') as fp: fp.write(DALS('\n <!DOCTYPE html><html><body>\n <a href="{dist_sdist}" rel="internal">{dist_sdist}</a><br/>\n </body></html>\n ').format(dist_sdist=dist_sdist)) sdist_with_index('barbazquux', '3.2.0') sdist_with_index('barbazquux-runner', '2.11.1') with tmpdir.join('setup.cfg').open('w') as fp: fp.write(DALS('\n [easy_install]\n index_url = {index_url}\n ').format(index_url=index_url)) reqs = '\n barbazquux-runner\n barbazquux\n '.split() with tmpdir.as_cwd(): dist = Distribution() dist.parse_config_files() resolved_dists = [dist.fetch_build_egg(r) for r in reqs] assert ([dist.key for dist in resolved_dists if dist] == reqs)
def test_dist_fetch_build_egg(tmpdir): '\n \n ' index = tmpdir.mkdir('index') index_url = urljoin('file://', pathname2url(str(index))) def sdist_with_index(distname, version): dist_dir = index.mkdir(distname) dist_sdist = ('%s-%s.tar.gz' % (distname, version)) make_nspkg_sdist(str(dist_dir.join(dist_sdist)), distname, version) with dist_dir.join('index.html').open('w') as fp: fp.write(DALS('\n <!DOCTYPE html><html><body>\n <a href="{dist_sdist}" rel="internal">{dist_sdist}</a><br/>\n </body></html>\n ').format(dist_sdist=dist_sdist)) sdist_with_index('barbazquux', '3.2.0') sdist_with_index('barbazquux-runner', '2.11.1') with tmpdir.join('setup.cfg').open('w') as fp: fp.write(DALS('\n [easy_install]\n index_url = {index_url}\n ').format(index_url=index_url)) reqs = '\n barbazquux-runner\n barbazquux\n '.split() with tmpdir.as_cwd(): dist = Distribution() dist.parse_config_files() resolved_dists = [dist.fetch_build_egg(r) for r in reqs] assert ([dist.key for dist in resolved_dists if dist] == reqs)<|docstring|>Check multiple calls to `Distribution.fetch_build_egg` work as expected.<|endoftext|>
0e35e698b9636040672cf864b8627df48715f5466e3fa6226afdde46fb3ced6e
async def message_handler(self, msg): 'Method as callback subscriber function' raise NotImplementedError('subclasses of NatsSubscriber must provide a message_handler() method')
Method as callback subscriber function
src/asyncio_nats_service/subscribers.py
message_handler
borisovcode/asyncio_nats_service.py
0
python
async def message_handler(self, msg): raise NotImplementedError('subclasses of NatsSubscriber must provide a message_handler() method')
async def message_handler(self, msg): raise NotImplementedError('subclasses of NatsSubscriber must provide a message_handler() method')<|docstring|>Method as callback subscriber function<|endoftext|>
243ed9f4e6d7b015079df1fcbe0c3e991b4e6a801694e9594c56000128fe17ca
@distributed_trace def list_by_project(self, dev_center, project_name, fidalgo_dns_suffix='devcenters.fidalgo.azure.com', top=None, **kwargs): 'Lists all environment types configured for a project.\n\n :param dev_center: The DevCenter to operate on.\n :type dev_center: str\n :param project_name: The Fidalgo Project upon which to execute operations.\n :type project_name: str\n :param fidalgo_dns_suffix: The DNS suffix used as the base for all fidalgo requests. Default\n value is "devcenters.fidalgo.azure.com".\n :type fidalgo_dns_suffix: str\n :param top: The maximum number of resources to return from the operation. Example: \'$top=10\'.\n Default value is None.\n :type top: int\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either EnvironmentTypeListResult or the result of\n cls(response)\n :rtype: ~azure.core.paging.ItemPaged[~azure.fidalgo.models.EnvironmentTypeListResult]\n :raises: ~azure.core.exceptions.HttpResponseError\n ' api_version = kwargs.pop('api_version', '2021-09-01-privatepreview') cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) def prepare_request(next_link=None): if (not next_link): request = build_list_by_project_request(project_name=project_name, api_version=api_version, top=top, template_url=self.list_by_project.metadata['url']) request = _convert_request(request) path_format_arguments = {'devCenter': self._serialize.url('dev_center', dev_center, 'str', skip_quote=True), 'fidalgoDnsSuffix': self._serialize.url('fidalgo_dns_suffix', fidalgo_dns_suffix, 'str', skip_quote=True)} request.url = self._client.format_url(request.url, **path_format_arguments) else: request = build_list_by_project_request(project_name=project_name, api_version=api_version, top=top, template_url=next_link) request = _convert_request(request) path_format_arguments = {'devCenter': self._serialize.url('dev_center', dev_center, 'str', skip_quote=True), 'fidalgoDnsSuffix': self._serialize.url('fidalgo_dns_suffix', fidalgo_dns_suffix, 'str', skip_quote=True)} request.url = self._client.format_url(request.url, **path_format_arguments) path_format_arguments = {'devCenter': self._serialize.url('dev_center', dev_center, 'str', skip_quote=True), 'fidalgoDnsSuffix': self._serialize.url('fidalgo_dns_suffix', fidalgo_dns_suffix, 'str', skip_quote=True)} request.method = 'GET' return request def extract_data(pipeline_response): deserialized = self._deserialize('EnvironmentTypeListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return ((deserialized.next_link or None), iter(list_of_elem)) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CloudError, pipeline_response) raise HttpResponseError(response=response, model=error) return pipeline_response return ItemPaged(get_next, extract_data)
Lists all environment types configured for a project. :param dev_center: The DevCenter to operate on. :type dev_center: str :param project_name: The Fidalgo Project upon which to execute operations. :type project_name: str :param fidalgo_dns_suffix: The DNS suffix used as the base for all fidalgo requests. Default value is "devcenters.fidalgo.azure.com". :type fidalgo_dns_suffix: str :param top: The maximum number of resources to return from the operation. Example: '$top=10'. Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either EnvironmentTypeListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.fidalgo.models.EnvironmentTypeListResult] :raises: ~azure.core.exceptions.HttpResponseError
src/fidalgo/azext_fidalgo/vendored_sdks/fidalgo_dataplane/operations/_environment_type_operations.py
list_by_project
tbyfield/azure-cli-extensions
0
python
@distributed_trace def list_by_project(self, dev_center, project_name, fidalgo_dns_suffix='devcenters.fidalgo.azure.com', top=None, **kwargs): 'Lists all environment types configured for a project.\n\n :param dev_center: The DevCenter to operate on.\n :type dev_center: str\n :param project_name: The Fidalgo Project upon which to execute operations.\n :type project_name: str\n :param fidalgo_dns_suffix: The DNS suffix used as the base for all fidalgo requests. Default\n value is "devcenters.fidalgo.azure.com".\n :type fidalgo_dns_suffix: str\n :param top: The maximum number of resources to return from the operation. Example: \'$top=10\'.\n Default value is None.\n :type top: int\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either EnvironmentTypeListResult or the result of\n cls(response)\n :rtype: ~azure.core.paging.ItemPaged[~azure.fidalgo.models.EnvironmentTypeListResult]\n :raises: ~azure.core.exceptions.HttpResponseError\n ' api_version = kwargs.pop('api_version', '2021-09-01-privatepreview') cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) def prepare_request(next_link=None): if (not next_link): request = build_list_by_project_request(project_name=project_name, api_version=api_version, top=top, template_url=self.list_by_project.metadata['url']) request = _convert_request(request) path_format_arguments = {'devCenter': self._serialize.url('dev_center', dev_center, 'str', skip_quote=True), 'fidalgoDnsSuffix': self._serialize.url('fidalgo_dns_suffix', fidalgo_dns_suffix, 'str', skip_quote=True)} request.url = self._client.format_url(request.url, **path_format_arguments) else: request = build_list_by_project_request(project_name=project_name, api_version=api_version, top=top, template_url=next_link) request = _convert_request(request) path_format_arguments = {'devCenter': self._serialize.url('dev_center', dev_center, 'str', skip_quote=True), 'fidalgoDnsSuffix': self._serialize.url('fidalgo_dns_suffix', fidalgo_dns_suffix, 'str', skip_quote=True)} request.url = self._client.format_url(request.url, **path_format_arguments) path_format_arguments = {'devCenter': self._serialize.url('dev_center', dev_center, 'str', skip_quote=True), 'fidalgoDnsSuffix': self._serialize.url('fidalgo_dns_suffix', fidalgo_dns_suffix, 'str', skip_quote=True)} request.method = 'GET' return request def extract_data(pipeline_response): deserialized = self._deserialize('EnvironmentTypeListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return ((deserialized.next_link or None), iter(list_of_elem)) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CloudError, pipeline_response) raise HttpResponseError(response=response, model=error) return pipeline_response return ItemPaged(get_next, extract_data)
@distributed_trace def list_by_project(self, dev_center, project_name, fidalgo_dns_suffix='devcenters.fidalgo.azure.com', top=None, **kwargs): 'Lists all environment types configured for a project.\n\n :param dev_center: The DevCenter to operate on.\n :type dev_center: str\n :param project_name: The Fidalgo Project upon which to execute operations.\n :type project_name: str\n :param fidalgo_dns_suffix: The DNS suffix used as the base for all fidalgo requests. Default\n value is "devcenters.fidalgo.azure.com".\n :type fidalgo_dns_suffix: str\n :param top: The maximum number of resources to return from the operation. Example: \'$top=10\'.\n Default value is None.\n :type top: int\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either EnvironmentTypeListResult or the result of\n cls(response)\n :rtype: ~azure.core.paging.ItemPaged[~azure.fidalgo.models.EnvironmentTypeListResult]\n :raises: ~azure.core.exceptions.HttpResponseError\n ' api_version = kwargs.pop('api_version', '2021-09-01-privatepreview') cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) def prepare_request(next_link=None): if (not next_link): request = build_list_by_project_request(project_name=project_name, api_version=api_version, top=top, template_url=self.list_by_project.metadata['url']) request = _convert_request(request) path_format_arguments = {'devCenter': self._serialize.url('dev_center', dev_center, 'str', skip_quote=True), 'fidalgoDnsSuffix': self._serialize.url('fidalgo_dns_suffix', fidalgo_dns_suffix, 'str', skip_quote=True)} request.url = self._client.format_url(request.url, **path_format_arguments) else: request = build_list_by_project_request(project_name=project_name, api_version=api_version, top=top, template_url=next_link) request = _convert_request(request) path_format_arguments = {'devCenter': self._serialize.url('dev_center', dev_center, 'str', skip_quote=True), 'fidalgoDnsSuffix': self._serialize.url('fidalgo_dns_suffix', fidalgo_dns_suffix, 'str', skip_quote=True)} request.url = self._client.format_url(request.url, **path_format_arguments) path_format_arguments = {'devCenter': self._serialize.url('dev_center', dev_center, 'str', skip_quote=True), 'fidalgoDnsSuffix': self._serialize.url('fidalgo_dns_suffix', fidalgo_dns_suffix, 'str', skip_quote=True)} request.method = 'GET' return request def extract_data(pipeline_response): deserialized = self._deserialize('EnvironmentTypeListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return ((deserialized.next_link or None), iter(list_of_elem)) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.CloudError, pipeline_response) raise HttpResponseError(response=response, model=error) return pipeline_response return ItemPaged(get_next, extract_data)<|docstring|>Lists all environment types configured for a project. :param dev_center: The DevCenter to operate on. :type dev_center: str :param project_name: The Fidalgo Project upon which to execute operations. :type project_name: str :param fidalgo_dns_suffix: The DNS suffix used as the base for all fidalgo requests. Default value is "devcenters.fidalgo.azure.com". :type fidalgo_dns_suffix: str :param top: The maximum number of resources to return from the operation. Example: '$top=10'. Default value is None. :type top: int :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either EnvironmentTypeListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.fidalgo.models.EnvironmentTypeListResult] :raises: ~azure.core.exceptions.HttpResponseError<|endoftext|>
d25b95cae386e5c3bfdfc520c6929acbcf29bad6217855182432403c5eb0f59c
def __init__(self, instance_id=None, endpoint=None): 'Endpoint - a model defined in Swagger' self._instance_id = None self._endpoint = None self.discriminator = None if (instance_id is not None): self.instance_id = instance_id if (endpoint is not None): self.endpoint = endpoint
Endpoint - a model defined in Swagger
swagger_client/models/endpoint.py
__init__
usmanager/registration-client-python
0
python
def __init__(self, instance_id=None, endpoint=None): self._instance_id = None self._endpoint = None self.discriminator = None if (instance_id is not None): self.instance_id = instance_id if (endpoint is not None): self.endpoint = endpoint
def __init__(self, instance_id=None, endpoint=None): self._instance_id = None self._endpoint = None self.discriminator = None if (instance_id is not None): self.instance_id = instance_id if (endpoint is not None): self.endpoint = endpoint<|docstring|>Endpoint - a model defined in Swagger<|endoftext|>
76d99ad63347c3a767fbc4640999900372e6458b76dbc777c4cafa076282437b
@property def instance_id(self): 'Gets the instance_id of this Endpoint. # noqa: E501\n\n\n :return: The instance_id of this Endpoint. # noqa: E501\n :rtype: str\n ' return self._instance_id
Gets the instance_id of this Endpoint. # noqa: E501 :return: The instance_id of this Endpoint. # noqa: E501 :rtype: str
swagger_client/models/endpoint.py
instance_id
usmanager/registration-client-python
0
python
@property def instance_id(self): 'Gets the instance_id of this Endpoint. # noqa: E501\n\n\n :return: The instance_id of this Endpoint. # noqa: E501\n :rtype: str\n ' return self._instance_id
@property def instance_id(self): 'Gets the instance_id of this Endpoint. # noqa: E501\n\n\n :return: The instance_id of this Endpoint. # noqa: E501\n :rtype: str\n ' return self._instance_id<|docstring|>Gets the instance_id of this Endpoint. # noqa: E501 :return: The instance_id of this Endpoint. # noqa: E501 :rtype: str<|endoftext|>
ae9e25cf59d23c7cdf112f6a1d9a45df53b73bd16c08f9ac72c20620482bbfec
@instance_id.setter def instance_id(self, instance_id): 'Sets the instance_id of this Endpoint.\n\n\n :param instance_id: The instance_id of this Endpoint. # noqa: E501\n :type: str\n ' self._instance_id = instance_id
Sets the instance_id of this Endpoint. :param instance_id: The instance_id of this Endpoint. # noqa: E501 :type: str
swagger_client/models/endpoint.py
instance_id
usmanager/registration-client-python
0
python
@instance_id.setter def instance_id(self, instance_id): 'Sets the instance_id of this Endpoint.\n\n\n :param instance_id: The instance_id of this Endpoint. # noqa: E501\n :type: str\n ' self._instance_id = instance_id
@instance_id.setter def instance_id(self, instance_id): 'Sets the instance_id of this Endpoint.\n\n\n :param instance_id: The instance_id of this Endpoint. # noqa: E501\n :type: str\n ' self._instance_id = instance_id<|docstring|>Sets the instance_id of this Endpoint. :param instance_id: The instance_id of this Endpoint. # noqa: E501 :type: str<|endoftext|>
95315c8c30abe80de00055f30597339db77fbea4bd471aa29e3bb096f0bb98bf
@property def endpoint(self): 'Gets the endpoint of this Endpoint. # noqa: E501\n\n\n :return: The endpoint of this Endpoint. # noqa: E501\n :rtype: str\n ' return self._endpoint
Gets the endpoint of this Endpoint. # noqa: E501 :return: The endpoint of this Endpoint. # noqa: E501 :rtype: str
swagger_client/models/endpoint.py
endpoint
usmanager/registration-client-python
0
python
@property def endpoint(self): 'Gets the endpoint of this Endpoint. # noqa: E501\n\n\n :return: The endpoint of this Endpoint. # noqa: E501\n :rtype: str\n ' return self._endpoint
@property def endpoint(self): 'Gets the endpoint of this Endpoint. # noqa: E501\n\n\n :return: The endpoint of this Endpoint. # noqa: E501\n :rtype: str\n ' return self._endpoint<|docstring|>Gets the endpoint of this Endpoint. # noqa: E501 :return: The endpoint of this Endpoint. # noqa: E501 :rtype: str<|endoftext|>
12afa9bb5127de2798fee587754820d3da71571c97e12a6e451a70b01544f8bf
@endpoint.setter def endpoint(self, endpoint): 'Sets the endpoint of this Endpoint.\n\n\n :param endpoint: The endpoint of this Endpoint. # noqa: E501\n :type: str\n ' self._endpoint = endpoint
Sets the endpoint of this Endpoint. :param endpoint: The endpoint of this Endpoint. # noqa: E501 :type: str
swagger_client/models/endpoint.py
endpoint
usmanager/registration-client-python
0
python
@endpoint.setter def endpoint(self, endpoint): 'Sets the endpoint of this Endpoint.\n\n\n :param endpoint: The endpoint of this Endpoint. # noqa: E501\n :type: str\n ' self._endpoint = endpoint
@endpoint.setter def endpoint(self, endpoint): 'Sets the endpoint of this Endpoint.\n\n\n :param endpoint: The endpoint of this Endpoint. # noqa: E501\n :type: str\n ' self._endpoint = endpoint<|docstring|>Sets the endpoint of this Endpoint. :param endpoint: The endpoint of this Endpoint. # noqa: E501 :type: str<|endoftext|>
38a425b3d10901b7e3dc6665779de4488648dbfa8b6eb8890c3fda278066c7e6
def to_dict(self): 'Returns the model properties as a dict' result = {} for (attr, _) in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value)) elif hasattr(value, 'to_dict'): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items())) else: result[attr] = value if issubclass(Endpoint, dict): for (key, value) in self.items(): result[key] = value return result
Returns the model properties as a dict
swagger_client/models/endpoint.py
to_dict
usmanager/registration-client-python
0
python
def to_dict(self): result = {} for (attr, _) in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value)) elif hasattr(value, 'to_dict'): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items())) else: result[attr] = value if issubclass(Endpoint, dict): for (key, value) in self.items(): result[key] = value return result
def to_dict(self): result = {} for (attr, _) in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value)) elif hasattr(value, 'to_dict'): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items())) else: result[attr] = value if issubclass(Endpoint, dict): for (key, value) in self.items(): result[key] = value return result<|docstring|>Returns the model properties as a dict<|endoftext|>
cbb19eaa2fc8a113d9e32f924ef280a7e97563f8915f94f65dab438997af2e99
def to_str(self): 'Returns the string representation of the model' return pprint.pformat(self.to_dict())
Returns the string representation of the model
swagger_client/models/endpoint.py
to_str
usmanager/registration-client-python
0
python
def to_str(self): return pprint.pformat(self.to_dict())
def to_str(self): return pprint.pformat(self.to_dict())<|docstring|>Returns the string representation of the model<|endoftext|>
772243a2c2b3261a9b954d07aaf295e3c1242a579a495e2d6a5679c677861703
def __repr__(self): 'For `print` and `pprint`' return self.to_str()
For `print` and `pprint`
swagger_client/models/endpoint.py
__repr__
usmanager/registration-client-python
0
python
def __repr__(self): return self.to_str()
def __repr__(self): return self.to_str()<|docstring|>For `print` and `pprint`<|endoftext|>
ac4f5d5385392f122f5a865d5ab53cd1ed2ada47cec1adeedfd3738d141bd079
def __eq__(self, other): 'Returns true if both objects are equal' if (not isinstance(other, Endpoint)): return False return (self.__dict__ == other.__dict__)
Returns true if both objects are equal
swagger_client/models/endpoint.py
__eq__
usmanager/registration-client-python
0
python
def __eq__(self, other): if (not isinstance(other, Endpoint)): return False return (self.__dict__ == other.__dict__)
def __eq__(self, other): if (not isinstance(other, Endpoint)): return False return (self.__dict__ == other.__dict__)<|docstring|>Returns true if both objects are equal<|endoftext|>
43dc6740163eb9fc1161d09cb2208a64c7ad0cc8d9c8637ac3264522d3ec7e42
def __ne__(self, other): 'Returns true if both objects are not equal' return (not (self == other))
Returns true if both objects are not equal
swagger_client/models/endpoint.py
__ne__
usmanager/registration-client-python
0
python
def __ne__(self, other): return (not (self == other))
def __ne__(self, other): return (not (self == other))<|docstring|>Returns true if both objects are not equal<|endoftext|>
2f6995f25df00820cc5213bfa0b342657dcad2e8e5fd4e43694a10f550259650
def validate_key_names(key_names_list): 'Validate each item of the list to match key name regex.' for key_name in key_names_list: if (not VALID_KEY_NAME_REGEX.match(key_name)): return False return True
Validate each item of the list to match key name regex.
manila/api/common.py
validate_key_names
peter-slovak/nexenta-manila
1
python
def validate_key_names(key_names_list): for key_name in key_names_list: if (not VALID_KEY_NAME_REGEX.match(key_name)): return False return True
def validate_key_names(key_names_list): for key_name in key_names_list: if (not VALID_KEY_NAME_REGEX.match(key_name)): return False return True<|docstring|>Validate each item of the list to match key name regex.<|endoftext|>
e17efb140cafd9c65e75c4ebdec4c195c491958b3f1317381d1d6352949f4ef6
def get_pagination_params(request): "Return marker, limit tuple from request.\n\n :param request: `wsgi.Request` possibly containing 'marker' and 'limit'\n GET variables. 'marker' is the id of the last element\n the client has seen, and 'limit' is the maximum number\n of items to return. If 'limit' is not specified, 0, or\n > max_limit, we default to max_limit. Negative values\n for either marker or limit will cause\n exc.HTTPBadRequest() exceptions to be raised.\n\n " params = {} if ('limit' in request.GET): params['limit'] = _get_limit_param(request) if ('marker' in request.GET): params['marker'] = _get_marker_param(request) return params
Return marker, limit tuple from request. :param request: `wsgi.Request` possibly containing 'marker' and 'limit' GET variables. 'marker' is the id of the last element the client has seen, and 'limit' is the maximum number of items to return. If 'limit' is not specified, 0, or > max_limit, we default to max_limit. Negative values for either marker or limit will cause exc.HTTPBadRequest() exceptions to be raised.
manila/api/common.py
get_pagination_params
peter-slovak/nexenta-manila
1
python
def get_pagination_params(request): "Return marker, limit tuple from request.\n\n :param request: `wsgi.Request` possibly containing 'marker' and 'limit'\n GET variables. 'marker' is the id of the last element\n the client has seen, and 'limit' is the maximum number\n of items to return. If 'limit' is not specified, 0, or\n > max_limit, we default to max_limit. Negative values\n for either marker or limit will cause\n exc.HTTPBadRequest() exceptions to be raised.\n\n " params = {} if ('limit' in request.GET): params['limit'] = _get_limit_param(request) if ('marker' in request.GET): params['marker'] = _get_marker_param(request) return params
def get_pagination_params(request): "Return marker, limit tuple from request.\n\n :param request: `wsgi.Request` possibly containing 'marker' and 'limit'\n GET variables. 'marker' is the id of the last element\n the client has seen, and 'limit' is the maximum number\n of items to return. If 'limit' is not specified, 0, or\n > max_limit, we default to max_limit. Negative values\n for either marker or limit will cause\n exc.HTTPBadRequest() exceptions to be raised.\n\n " params = {} if ('limit' in request.GET): params['limit'] = _get_limit_param(request) if ('marker' in request.GET): params['marker'] = _get_marker_param(request) return params<|docstring|>Return marker, limit tuple from request. :param request: `wsgi.Request` possibly containing 'marker' and 'limit' GET variables. 'marker' is the id of the last element the client has seen, and 'limit' is the maximum number of items to return. If 'limit' is not specified, 0, or > max_limit, we default to max_limit. Negative values for either marker or limit will cause exc.HTTPBadRequest() exceptions to be raised.<|endoftext|>
eff21551767d642976a1763b77d6d4b59d74d6d48cd9c7d8b4b29ffe4b2e806a
def _get_limit_param(request): 'Extract integer limit from request or fail.' try: limit = int(request.GET['limit']) except ValueError: msg = _('limit param must be an integer') raise webob.exc.HTTPBadRequest(explanation=msg) if (limit < 0): msg = _('limit param must be positive') raise webob.exc.HTTPBadRequest(explanation=msg) return limit
Extract integer limit from request or fail.
manila/api/common.py
_get_limit_param
peter-slovak/nexenta-manila
1
python
def _get_limit_param(request): try: limit = int(request.GET['limit']) except ValueError: msg = _('limit param must be an integer') raise webob.exc.HTTPBadRequest(explanation=msg) if (limit < 0): msg = _('limit param must be positive') raise webob.exc.HTTPBadRequest(explanation=msg) return limit
def _get_limit_param(request): try: limit = int(request.GET['limit']) except ValueError: msg = _('limit param must be an integer') raise webob.exc.HTTPBadRequest(explanation=msg) if (limit < 0): msg = _('limit param must be positive') raise webob.exc.HTTPBadRequest(explanation=msg) return limit<|docstring|>Extract integer limit from request or fail.<|endoftext|>
b17c6a8670c2f8093effe7b3a404c96bd7609b16bcd0619a515b6ad2aea48383
def _get_marker_param(request): 'Extract marker ID from request or fail.' return request.GET['marker']
Extract marker ID from request or fail.
manila/api/common.py
_get_marker_param
peter-slovak/nexenta-manila
1
python
def _get_marker_param(request): return request.GET['marker']
def _get_marker_param(request): return request.GET['marker']<|docstring|>Extract marker ID from request or fail.<|endoftext|>
c9199a91412b14138616fe8272be509546938540004adea9f78e3627c2be19e3
def limited(items, request, max_limit=CONF.osapi_max_limit): "Return a slice of items according to requested offset and limit.\n\n :param items: A sliceable entity\n :param request: ``wsgi.Request`` possibly containing 'offset' and 'limit'\n GET variables. 'offset' is where to start in the list,\n and 'limit' is the maximum number of items to return. If\n 'limit' is not specified, 0, or > max_limit, we default\n to max_limit. Negative values for either offset or limit\n will cause exc.HTTPBadRequest() exceptions to be raised.\n :kwarg max_limit: The maximum number of items to return from 'items'\n " try: offset = int(request.GET.get('offset', 0)) except ValueError: msg = _('offset param must be an integer') raise webob.exc.HTTPBadRequest(explanation=msg) try: limit = int(request.GET.get('limit', max_limit)) except ValueError: msg = _('limit param must be an integer') raise webob.exc.HTTPBadRequest(explanation=msg) if (limit < 0): msg = _('limit param must be positive') raise webob.exc.HTTPBadRequest(explanation=msg) if (offset < 0): msg = _('offset param must be positive') raise webob.exc.HTTPBadRequest(explanation=msg) limit = min(max_limit, (limit or max_limit)) range_end = (offset + limit) return items[offset:range_end]
Return a slice of items according to requested offset and limit. :param items: A sliceable entity :param request: ``wsgi.Request`` possibly containing 'offset' and 'limit' GET variables. 'offset' is where to start in the list, and 'limit' is the maximum number of items to return. If 'limit' is not specified, 0, or > max_limit, we default to max_limit. Negative values for either offset or limit will cause exc.HTTPBadRequest() exceptions to be raised. :kwarg max_limit: The maximum number of items to return from 'items'
manila/api/common.py
limited
peter-slovak/nexenta-manila
1
python
def limited(items, request, max_limit=CONF.osapi_max_limit): "Return a slice of items according to requested offset and limit.\n\n :param items: A sliceable entity\n :param request: ``wsgi.Request`` possibly containing 'offset' and 'limit'\n GET variables. 'offset' is where to start in the list,\n and 'limit' is the maximum number of items to return. If\n 'limit' is not specified, 0, or > max_limit, we default\n to max_limit. Negative values for either offset or limit\n will cause exc.HTTPBadRequest() exceptions to be raised.\n :kwarg max_limit: The maximum number of items to return from 'items'\n " try: offset = int(request.GET.get('offset', 0)) except ValueError: msg = _('offset param must be an integer') raise webob.exc.HTTPBadRequest(explanation=msg) try: limit = int(request.GET.get('limit', max_limit)) except ValueError: msg = _('limit param must be an integer') raise webob.exc.HTTPBadRequest(explanation=msg) if (limit < 0): msg = _('limit param must be positive') raise webob.exc.HTTPBadRequest(explanation=msg) if (offset < 0): msg = _('offset param must be positive') raise webob.exc.HTTPBadRequest(explanation=msg) limit = min(max_limit, (limit or max_limit)) range_end = (offset + limit) return items[offset:range_end]
def limited(items, request, max_limit=CONF.osapi_max_limit): "Return a slice of items according to requested offset and limit.\n\n :param items: A sliceable entity\n :param request: ``wsgi.Request`` possibly containing 'offset' and 'limit'\n GET variables. 'offset' is where to start in the list,\n and 'limit' is the maximum number of items to return. If\n 'limit' is not specified, 0, or > max_limit, we default\n to max_limit. Negative values for either offset or limit\n will cause exc.HTTPBadRequest() exceptions to be raised.\n :kwarg max_limit: The maximum number of items to return from 'items'\n " try: offset = int(request.GET.get('offset', 0)) except ValueError: msg = _('offset param must be an integer') raise webob.exc.HTTPBadRequest(explanation=msg) try: limit = int(request.GET.get('limit', max_limit)) except ValueError: msg = _('limit param must be an integer') raise webob.exc.HTTPBadRequest(explanation=msg) if (limit < 0): msg = _('limit param must be positive') raise webob.exc.HTTPBadRequest(explanation=msg) if (offset < 0): msg = _('offset param must be positive') raise webob.exc.HTTPBadRequest(explanation=msg) limit = min(max_limit, (limit or max_limit)) range_end = (offset + limit) return items[offset:range_end]<|docstring|>Return a slice of items according to requested offset and limit. :param items: A sliceable entity :param request: ``wsgi.Request`` possibly containing 'offset' and 'limit' GET variables. 'offset' is where to start in the list, and 'limit' is the maximum number of items to return. If 'limit' is not specified, 0, or > max_limit, we default to max_limit. Negative values for either offset or limit will cause exc.HTTPBadRequest() exceptions to be raised. :kwarg max_limit: The maximum number of items to return from 'items'<|endoftext|>
072478878bfe4c52df2328c85b0c0210be0844117fb43b92e316d3397d3f69c8
def limited_by_marker(items, request, max_limit=CONF.osapi_max_limit): 'Return a slice of items according to the requested marker and limit.' params = get_pagination_params(request) limit = params.get('limit', max_limit) marker = params.get('marker') limit = min(max_limit, limit) start_index = 0 if marker: start_index = (- 1) for (i, item) in enumerate(items): if ('flavorid' in item): if (item['flavorid'] == marker): start_index = (i + 1) break elif ((item['id'] == marker) or (item.get('uuid') == marker)): start_index = (i + 1) break if (start_index < 0): msg = (_('marker [%s] not found') % marker) raise webob.exc.HTTPBadRequest(explanation=msg) range_end = (start_index + limit) return items[start_index:range_end]
Return a slice of items according to the requested marker and limit.
manila/api/common.py
limited_by_marker
peter-slovak/nexenta-manila
1
python
def limited_by_marker(items, request, max_limit=CONF.osapi_max_limit): params = get_pagination_params(request) limit = params.get('limit', max_limit) marker = params.get('marker') limit = min(max_limit, limit) start_index = 0 if marker: start_index = (- 1) for (i, item) in enumerate(items): if ('flavorid' in item): if (item['flavorid'] == marker): start_index = (i + 1) break elif ((item['id'] == marker) or (item.get('uuid') == marker)): start_index = (i + 1) break if (start_index < 0): msg = (_('marker [%s] not found') % marker) raise webob.exc.HTTPBadRequest(explanation=msg) range_end = (start_index + limit) return items[start_index:range_end]
def limited_by_marker(items, request, max_limit=CONF.osapi_max_limit): params = get_pagination_params(request) limit = params.get('limit', max_limit) marker = params.get('marker') limit = min(max_limit, limit) start_index = 0 if marker: start_index = (- 1) for (i, item) in enumerate(items): if ('flavorid' in item): if (item['flavorid'] == marker): start_index = (i + 1) break elif ((item['id'] == marker) or (item.get('uuid') == marker)): start_index = (i + 1) break if (start_index < 0): msg = (_('marker [%s] not found') % marker) raise webob.exc.HTTPBadRequest(explanation=msg) range_end = (start_index + limit) return items[start_index:range_end]<|docstring|>Return a slice of items according to the requested marker and limit.<|endoftext|>
98dbcd4895fd760cbdb6ceeaba12eb3d95299c43f2f08a227378023f0411e49a
def remove_version_from_href(href): "Removes the first api version from the href.\n\n Given: 'http://www.manila.com/v1.1/123'\n Returns: 'http://www.manila.com/123'\n\n Given: 'http://www.manila.com/v1.1'\n Returns: 'http://www.manila.com'\n\n " parsed_url = parse.urlsplit(href) url_parts = parsed_url.path.split('/', 2) expression = re.compile('^v([0-9]+|[0-9]+\\.[0-9]+)(/.*|$)') if expression.match(url_parts[1]): del url_parts[1] new_path = '/'.join(url_parts) if (new_path == parsed_url.path): msg = ('href %s does not contain version' % href) LOG.debug(msg) raise ValueError(msg) parsed_url = list(parsed_url) parsed_url[2] = new_path return parse.urlunsplit(parsed_url)
Removes the first api version from the href. Given: 'http://www.manila.com/v1.1/123' Returns: 'http://www.manila.com/123' Given: 'http://www.manila.com/v1.1' Returns: 'http://www.manila.com'
manila/api/common.py
remove_version_from_href
peter-slovak/nexenta-manila
1
python
def remove_version_from_href(href): "Removes the first api version from the href.\n\n Given: 'http://www.manila.com/v1.1/123'\n Returns: 'http://www.manila.com/123'\n\n Given: 'http://www.manila.com/v1.1'\n Returns: 'http://www.manila.com'\n\n " parsed_url = parse.urlsplit(href) url_parts = parsed_url.path.split('/', 2) expression = re.compile('^v([0-9]+|[0-9]+\\.[0-9]+)(/.*|$)') if expression.match(url_parts[1]): del url_parts[1] new_path = '/'.join(url_parts) if (new_path == parsed_url.path): msg = ('href %s does not contain version' % href) LOG.debug(msg) raise ValueError(msg) parsed_url = list(parsed_url) parsed_url[2] = new_path return parse.urlunsplit(parsed_url)
def remove_version_from_href(href): "Removes the first api version from the href.\n\n Given: 'http://www.manila.com/v1.1/123'\n Returns: 'http://www.manila.com/123'\n\n Given: 'http://www.manila.com/v1.1'\n Returns: 'http://www.manila.com'\n\n " parsed_url = parse.urlsplit(href) url_parts = parsed_url.path.split('/', 2) expression = re.compile('^v([0-9]+|[0-9]+\\.[0-9]+)(/.*|$)') if expression.match(url_parts[1]): del url_parts[1] new_path = '/'.join(url_parts) if (new_path == parsed_url.path): msg = ('href %s does not contain version' % href) LOG.debug(msg) raise ValueError(msg) parsed_url = list(parsed_url) parsed_url[2] = new_path return parse.urlunsplit(parsed_url)<|docstring|>Removes the first api version from the href. Given: 'http://www.manila.com/v1.1/123' Returns: 'http://www.manila.com/123' Given: 'http://www.manila.com/v1.1' Returns: 'http://www.manila.com'<|endoftext|>
75e2e06f85c829aa2b7befcb8052de52dff19d2cbcf752f1c003b7efd2f77c6b
def remove_invalid_options(context, search_options, allowed_search_options): 'Remove search options that are not valid for non-admin API/context.' if context.is_admin: return unknown_options = [opt for opt in search_options if (opt not in allowed_search_options)] bad_options = ', '.join(unknown_options) LOG.debug("Removing options '%(bad_options)s' from query", {'bad_options': bad_options}) for opt in unknown_options: del search_options[opt]
Remove search options that are not valid for non-admin API/context.
manila/api/common.py
remove_invalid_options
peter-slovak/nexenta-manila
1
python
def remove_invalid_options(context, search_options, allowed_search_options): if context.is_admin: return unknown_options = [opt for opt in search_options if (opt not in allowed_search_options)] bad_options = ', '.join(unknown_options) LOG.debug("Removing options '%(bad_options)s' from query", {'bad_options': bad_options}) for opt in unknown_options: del search_options[opt]
def remove_invalid_options(context, search_options, allowed_search_options): if context.is_admin: return unknown_options = [opt for opt in search_options if (opt not in allowed_search_options)] bad_options = ', '.join(unknown_options) LOG.debug("Removing options '%(bad_options)s' from query", {'bad_options': bad_options}) for opt in unknown_options: del search_options[opt]<|docstring|>Remove search options that are not valid for non-admin API/context.<|endoftext|>
c474edd68eb4945428b3fa2a096531f7e2ea6dbd9ab0c278be1c0686bd6314b5
def _get_next_link(self, request, identifier): 'Return href string with proper limit and marker params.' params = request.params.copy() params['marker'] = identifier prefix = self._update_link_prefix(request.application_url, CONF.osapi_share_base_URL) url = os.path.join(prefix, request.environ['manila.context'].project_id, self._collection_name) return ('%s?%s' % (url, dict_to_query_str(params)))
Return href string with proper limit and marker params.
manila/api/common.py
_get_next_link
peter-slovak/nexenta-manila
1
python
def _get_next_link(self, request, identifier): params = request.params.copy() params['marker'] = identifier prefix = self._update_link_prefix(request.application_url, CONF.osapi_share_base_URL) url = os.path.join(prefix, request.environ['manila.context'].project_id, self._collection_name) return ('%s?%s' % (url, dict_to_query_str(params)))
def _get_next_link(self, request, identifier): params = request.params.copy() params['marker'] = identifier prefix = self._update_link_prefix(request.application_url, CONF.osapi_share_base_URL) url = os.path.join(prefix, request.environ['manila.context'].project_id, self._collection_name) return ('%s?%s' % (url, dict_to_query_str(params)))<|docstring|>Return href string with proper limit and marker params.<|endoftext|>
1b970378031cb68570c154cddec8496e463ad118b4f84ba6746267866ebe7c81
def _get_href_link(self, request, identifier): 'Return an href string pointing to this object.' prefix = self._update_link_prefix(request.application_url, CONF.osapi_share_base_URL) return os.path.join(prefix, request.environ['manila.context'].project_id, self._collection_name, str(identifier))
Return an href string pointing to this object.
manila/api/common.py
_get_href_link
peter-slovak/nexenta-manila
1
python
def _get_href_link(self, request, identifier): prefix = self._update_link_prefix(request.application_url, CONF.osapi_share_base_URL) return os.path.join(prefix, request.environ['manila.context'].project_id, self._collection_name, str(identifier))
def _get_href_link(self, request, identifier): prefix = self._update_link_prefix(request.application_url, CONF.osapi_share_base_URL) return os.path.join(prefix, request.environ['manila.context'].project_id, self._collection_name, str(identifier))<|docstring|>Return an href string pointing to this object.<|endoftext|>
d508100f500c7d8ed04c465a3d563bc80963d61236e9e58a337547f5d304cc71
def _get_bookmark_link(self, request, identifier): 'Create a URL that refers to a specific resource.' base_url = remove_version_from_href(request.application_url) base_url = self._update_link_prefix(base_url, CONF.osapi_share_base_URL) return os.path.join(base_url, request.environ['manila.context'].project_id, self._collection_name, str(identifier))
Create a URL that refers to a specific resource.
manila/api/common.py
_get_bookmark_link
peter-slovak/nexenta-manila
1
python
def _get_bookmark_link(self, request, identifier): base_url = remove_version_from_href(request.application_url) base_url = self._update_link_prefix(base_url, CONF.osapi_share_base_URL) return os.path.join(base_url, request.environ['manila.context'].project_id, self._collection_name, str(identifier))
def _get_bookmark_link(self, request, identifier): base_url = remove_version_from_href(request.application_url) base_url = self._update_link_prefix(base_url, CONF.osapi_share_base_URL) return os.path.join(base_url, request.environ['manila.context'].project_id, self._collection_name, str(identifier))<|docstring|>Create a URL that refers to a specific resource.<|endoftext|>
9c8fcf3682bc02f85df41c9730adf8115de9366f267cb2707fff91d018d5a45b
def _get_collection_links(self, request, items, id_key='uuid'): "Retrieve 'next' link, if applicable." links = [] limit = int(request.params.get('limit', 0)) if (limit and (limit == len(items))): last_item = items[(- 1)] if (id_key in last_item): last_item_id = last_item[id_key] else: last_item_id = last_item['id'] links.append({'rel': 'next', 'href': self._get_next_link(request, last_item_id)}) return links
Retrieve 'next' link, if applicable.
manila/api/common.py
_get_collection_links
peter-slovak/nexenta-manila
1
python
def _get_collection_links(self, request, items, id_key='uuid'): links = [] limit = int(request.params.get('limit', 0)) if (limit and (limit == len(items))): last_item = items[(- 1)] if (id_key in last_item): last_item_id = last_item[id_key] else: last_item_id = last_item['id'] links.append({'rel': 'next', 'href': self._get_next_link(request, last_item_id)}) return links
def _get_collection_links(self, request, items, id_key='uuid'): links = [] limit = int(request.params.get('limit', 0)) if (limit and (limit == len(items))): last_item = items[(- 1)] if (id_key in last_item): last_item_id = last_item[id_key] else: last_item_id = last_item['id'] links.append({'rel': 'next', 'href': self._get_next_link(request, last_item_id)}) return links<|docstring|>Retrieve 'next' link, if applicable.<|endoftext|>
bfcc08f650c779ced67648a47833486b2fbfd98b414debc87b87eb7d8b38a128
def update_versioned_resource_dict(self, request, resource_dict, resource): 'Updates teh given resource dict for the given request version.\n\n This method calls every method, that is applicable to the request\n version, in _detail_version_modifiers.\n ' for method_name in self._detail_version_modifiers: method = getattr(self, method_name) if request.api_version_request.matches_versioned_method(method): method.func(self, resource_dict, resource)
Updates teh given resource dict for the given request version. This method calls every method, that is applicable to the request version, in _detail_version_modifiers.
manila/api/common.py
update_versioned_resource_dict
peter-slovak/nexenta-manila
1
python
def update_versioned_resource_dict(self, request, resource_dict, resource): 'Updates teh given resource dict for the given request version.\n\n This method calls every method, that is applicable to the request\n version, in _detail_version_modifiers.\n ' for method_name in self._detail_version_modifiers: method = getattr(self, method_name) if request.api_version_request.matches_versioned_method(method): method.func(self, resource_dict, resource)
def update_versioned_resource_dict(self, request, resource_dict, resource): 'Updates teh given resource dict for the given request version.\n\n This method calls every method, that is applicable to the request\n version, in _detail_version_modifiers.\n ' for method_name in self._detail_version_modifiers: method = getattr(self, method_name) if request.api_version_request.matches_versioned_method(method): method.func(self, resource_dict, resource)<|docstring|>Updates teh given resource dict for the given request version. This method calls every method, that is applicable to the request version, in _detail_version_modifiers.<|endoftext|>
e4cbb8c8f5cb7a5e1da7dcbef96699d21f59c280cf47f33e80aa3ecc018f34e6
@classmethod def versioned_method(cls, min_ver, max_ver=None, experimental=False): 'Decorator for versioning API methods.\n\n :param min_ver: string representing minimum version\n :param max_ver: optional string representing maximum version\n :param experimental: flag indicating an API is experimental and is\n subject to change or removal at any time\n ' def decorator(f): obj_min_ver = api_version.APIVersionRequest(min_ver) if max_ver: obj_max_ver = api_version.APIVersionRequest(max_ver) else: obj_max_ver = api_version.APIVersionRequest() func_name = f.__name__ new_func = versioned_method.VersionedMethod(func_name, obj_min_ver, obj_max_ver, experimental, f) return new_func return decorator
Decorator for versioning API methods. :param min_ver: string representing minimum version :param max_ver: optional string representing maximum version :param experimental: flag indicating an API is experimental and is subject to change or removal at any time
manila/api/common.py
versioned_method
peter-slovak/nexenta-manila
1
python
@classmethod def versioned_method(cls, min_ver, max_ver=None, experimental=False): 'Decorator for versioning API methods.\n\n :param min_ver: string representing minimum version\n :param max_ver: optional string representing maximum version\n :param experimental: flag indicating an API is experimental and is\n subject to change or removal at any time\n ' def decorator(f): obj_min_ver = api_version.APIVersionRequest(min_ver) if max_ver: obj_max_ver = api_version.APIVersionRequest(max_ver) else: obj_max_ver = api_version.APIVersionRequest() func_name = f.__name__ new_func = versioned_method.VersionedMethod(func_name, obj_min_ver, obj_max_ver, experimental, f) return new_func return decorator
@classmethod def versioned_method(cls, min_ver, max_ver=None, experimental=False): 'Decorator for versioning API methods.\n\n :param min_ver: string representing minimum version\n :param max_ver: optional string representing maximum version\n :param experimental: flag indicating an API is experimental and is\n subject to change or removal at any time\n ' def decorator(f): obj_min_ver = api_version.APIVersionRequest(min_ver) if max_ver: obj_max_ver = api_version.APIVersionRequest(max_ver) else: obj_max_ver = api_version.APIVersionRequest() func_name = f.__name__ new_func = versioned_method.VersionedMethod(func_name, obj_min_ver, obj_max_ver, experimental, f) return new_func return decorator<|docstring|>Decorator for versioning API methods. :param min_ver: string representing minimum version :param max_ver: optional string representing maximum version :param experimental: flag indicating an API is experimental and is subject to change or removal at any time<|endoftext|>
f41d18d7915b97b5fede1a043383252a5f4d08f0eacb80104fa2d396825d03be
def anonymize_ip(address, ipv4_mask=u'255.255.255.0', ipv6_mask=u'0000:0000:0000:0000:0000:0000:0000:0000'): '\n Anonymize the provided IPv4 or IPv6 address by setting parts of the\n address to 0\n :param str|int address: IP address to be anonymized\n :param str ipv4_mask: Mask that defines which parts of an IPv4 address are\n set to 0 (default: "255.255.255.0")\n :param str ipv6_mask: Mask that defines which parts of an IPv6 address are\n set to 0 (default: "0000:0000:0000:0000:0000:0000:0000:0000")\n :return: Anonymized IP address\n :rtype: str\n ' address_packed = ip_address(six.text_type(address)).packed address_len = len(address_packed) if (address_len == 4): ipv4_mask_packed = ip_address(ipv4_mask).packed __validate_ipv4_mask(ipv4_mask_packed) return __apply_mask(address_packed, ipv4_mask_packed, 4) elif (address_len == 16): ipv6_mask_packed = ip_address(ipv6_mask).packed __validate_ipv6_mask(ipv6_mask_packed) return __apply_mask(address_packed, ipv6_mask_packed, 16) else: raise ValueError('Address does not consist of 4 (IPv4) or 16 (IPv6) octets')
Anonymize the provided IPv4 or IPv6 address by setting parts of the address to 0 :param str|int address: IP address to be anonymized :param str ipv4_mask: Mask that defines which parts of an IPv4 address are set to 0 (default: "255.255.255.0") :param str ipv6_mask: Mask that defines which parts of an IPv6 address are set to 0 (default: "0000:0000:0000:0000:0000:0000:0000:0000") :return: Anonymized IP address :rtype: str
src/sentry_plugins/anonymizeip.py
anonymize_ip
pawelkoston/sentry-plugins
0
python
def anonymize_ip(address, ipv4_mask=u'255.255.255.0', ipv6_mask=u'0000:0000:0000:0000:0000:0000:0000:0000'): '\n Anonymize the provided IPv4 or IPv6 address by setting parts of the\n address to 0\n :param str|int address: IP address to be anonymized\n :param str ipv4_mask: Mask that defines which parts of an IPv4 address are\n set to 0 (default: "255.255.255.0")\n :param str ipv6_mask: Mask that defines which parts of an IPv6 address are\n set to 0 (default: "0000:0000:0000:0000:0000:0000:0000:0000")\n :return: Anonymized IP address\n :rtype: str\n ' address_packed = ip_address(six.text_type(address)).packed address_len = len(address_packed) if (address_len == 4): ipv4_mask_packed = ip_address(ipv4_mask).packed __validate_ipv4_mask(ipv4_mask_packed) return __apply_mask(address_packed, ipv4_mask_packed, 4) elif (address_len == 16): ipv6_mask_packed = ip_address(ipv6_mask).packed __validate_ipv6_mask(ipv6_mask_packed) return __apply_mask(address_packed, ipv6_mask_packed, 16) else: raise ValueError('Address does not consist of 4 (IPv4) or 16 (IPv6) octets')
def anonymize_ip(address, ipv4_mask=u'255.255.255.0', ipv6_mask=u'0000:0000:0000:0000:0000:0000:0000:0000'): '\n Anonymize the provided IPv4 or IPv6 address by setting parts of the\n address to 0\n :param str|int address: IP address to be anonymized\n :param str ipv4_mask: Mask that defines which parts of an IPv4 address are\n set to 0 (default: "255.255.255.0")\n :param str ipv6_mask: Mask that defines which parts of an IPv6 address are\n set to 0 (default: "0000:0000:0000:0000:0000:0000:0000:0000")\n :return: Anonymized IP address\n :rtype: str\n ' address_packed = ip_address(six.text_type(address)).packed address_len = len(address_packed) if (address_len == 4): ipv4_mask_packed = ip_address(ipv4_mask).packed __validate_ipv4_mask(ipv4_mask_packed) return __apply_mask(address_packed, ipv4_mask_packed, 4) elif (address_len == 16): ipv6_mask_packed = ip_address(ipv6_mask).packed __validate_ipv6_mask(ipv6_mask_packed) return __apply_mask(address_packed, ipv6_mask_packed, 16) else: raise ValueError('Address does not consist of 4 (IPv4) or 16 (IPv6) octets')<|docstring|>Anonymize the provided IPv4 or IPv6 address by setting parts of the address to 0 :param str|int address: IP address to be anonymized :param str ipv4_mask: Mask that defines which parts of an IPv4 address are set to 0 (default: "255.255.255.0") :param str ipv6_mask: Mask that defines which parts of an IPv6 address are set to 0 (default: "0000:0000:0000:0000:0000:0000:0000:0000") :return: Anonymized IP address :rtype: str<|endoftext|>
ef04c50dcfd6a086162c559d7836cb40a84489ccb4d9bedcbcb697556599d5e9
def __apply_mask(address_packed, mask_packed, nr_bytes): '\n Perform a bitwise AND operation on all corresponding bytes between the\n mask and the provided address. Mask parts set to 0 will become 0 in the\n anonymized IP address as well\n :param bytes address_packed: Binary representation of the IP address to\n be anonymized\n :param bytes mask_packed: Binary representation of the corresponding IP\n address mask\n :param int nr_bytes: Number of bytes in the address (4 for IPv4, 16 for\n IPv6)\n :return: Anonymized IP address\n :rtype: str\n ' anon_packed = bytearray() for i in range(0, nr_bytes): anon_packed.append((ord(mask_packed[i]) & ord(address_packed[i]))) return six.text_type(ip_address(six.binary_type(anon_packed)))
Perform a bitwise AND operation on all corresponding bytes between the mask and the provided address. Mask parts set to 0 will become 0 in the anonymized IP address as well :param bytes address_packed: Binary representation of the IP address to be anonymized :param bytes mask_packed: Binary representation of the corresponding IP address mask :param int nr_bytes: Number of bytes in the address (4 for IPv4, 16 for IPv6) :return: Anonymized IP address :rtype: str
src/sentry_plugins/anonymizeip.py
__apply_mask
pawelkoston/sentry-plugins
0
python
def __apply_mask(address_packed, mask_packed, nr_bytes): '\n Perform a bitwise AND operation on all corresponding bytes between the\n mask and the provided address. Mask parts set to 0 will become 0 in the\n anonymized IP address as well\n :param bytes address_packed: Binary representation of the IP address to\n be anonymized\n :param bytes mask_packed: Binary representation of the corresponding IP\n address mask\n :param int nr_bytes: Number of bytes in the address (4 for IPv4, 16 for\n IPv6)\n :return: Anonymized IP address\n :rtype: str\n ' anon_packed = bytearray() for i in range(0, nr_bytes): anon_packed.append((ord(mask_packed[i]) & ord(address_packed[i]))) return six.text_type(ip_address(six.binary_type(anon_packed)))
def __apply_mask(address_packed, mask_packed, nr_bytes): '\n Perform a bitwise AND operation on all corresponding bytes between the\n mask and the provided address. Mask parts set to 0 will become 0 in the\n anonymized IP address as well\n :param bytes address_packed: Binary representation of the IP address to\n be anonymized\n :param bytes mask_packed: Binary representation of the corresponding IP\n address mask\n :param int nr_bytes: Number of bytes in the address (4 for IPv4, 16 for\n IPv6)\n :return: Anonymized IP address\n :rtype: str\n ' anon_packed = bytearray() for i in range(0, nr_bytes): anon_packed.append((ord(mask_packed[i]) & ord(address_packed[i]))) return six.text_type(ip_address(six.binary_type(anon_packed)))<|docstring|>Perform a bitwise AND operation on all corresponding bytes between the mask and the provided address. Mask parts set to 0 will become 0 in the anonymized IP address as well :param bytes address_packed: Binary representation of the IP address to be anonymized :param bytes mask_packed: Binary representation of the corresponding IP address mask :param int nr_bytes: Number of bytes in the address (4 for IPv4, 16 for IPv6) :return: Anonymized IP address :rtype: str<|endoftext|>
4c5825dde25f7684ddaf7931d3c9bfdea54630f393b530fedecf608908d07da7
def __init__(self, init=0, minval=(- 1), maxval=1, sigma=1, fix=False, center=None, beta=None, name='param'): '\n\n :param init: initial value for parameter\n :param minval: min value\n :param maxval: max value\n :param sigma: refinement sensitivity factor\n :param fix: whether to fix the parameter\n :param center: restraint center\n :param beta: restraint variance (smaller values give rise to tighter restraints)\n :param name: str, an optional name for this parameter, for bookkeeping\n ' self.minval = minval self.maxval = maxval self.sigma = sigma self.init = init self.fix = fix self.center = center self.beta = beta self.name = name self._current_val = None self.xpos = 0 if fix: self.minval = (init - 1e-10) self.maxval = (init + 1e-10) self._arcsin_term = None
:param init: initial value for parameter :param minval: min value :param maxval: max value :param sigma: refinement sensitivity factor :param fix: whether to fix the parameter :param center: restraint center :param beta: restraint variance (smaller values give rise to tighter restraints) :param name: str, an optional name for this parameter, for bookkeeping
simtbx/diffBragg/refiners/parameters.py
__init__
GotthardG/cctbx_project
155
python
def __init__(self, init=0, minval=(- 1), maxval=1, sigma=1, fix=False, center=None, beta=None, name='param'): '\n\n :param init: initial value for parameter\n :param minval: min value\n :param maxval: max value\n :param sigma: refinement sensitivity factor\n :param fix: whether to fix the parameter\n :param center: restraint center\n :param beta: restraint variance (smaller values give rise to tighter restraints)\n :param name: str, an optional name for this parameter, for bookkeeping\n ' self.minval = minval self.maxval = maxval self.sigma = sigma self.init = init self.fix = fix self.center = center self.beta = beta self.name = name self._current_val = None self.xpos = 0 if fix: self.minval = (init - 1e-10) self.maxval = (init + 1e-10) self._arcsin_term = None
def __init__(self, init=0, minval=(- 1), maxval=1, sigma=1, fix=False, center=None, beta=None, name='param'): '\n\n :param init: initial value for parameter\n :param minval: min value\n :param maxval: max value\n :param sigma: refinement sensitivity factor\n :param fix: whether to fix the parameter\n :param center: restraint center\n :param beta: restraint variance (smaller values give rise to tighter restraints)\n :param name: str, an optional name for this parameter, for bookkeeping\n ' self.minval = minval self.maxval = maxval self.sigma = sigma self.init = init self.fix = fix self.center = center self.beta = beta self.name = name self._current_val = None self.xpos = 0 if fix: self.minval = (init - 1e-10) self.maxval = (init + 1e-10) self._arcsin_term = None<|docstring|>:param init: initial value for parameter :param minval: min value :param maxval: max value :param sigma: refinement sensitivity factor :param fix: whether to fix the parameter :param center: restraint center :param beta: restraint variance (smaller values give rise to tighter restraints) :param name: str, an optional name for this parameter, for bookkeeping<|endoftext|>
7f1c22c7b55c90591d437d0f230c2b7a1021c5a4537a1574199045d041c8d853
def _correction_map(pixel_radius_correction, array_shape, pointing_centre): "\n Args\n ----\n curve: function f(r)\n mapping radius *in pixels* from centre -> pb. corr. value.\n shape: numpy.ndarray.shape\n Shape of the numpy array to generate (2D)\n pointing_centre: tuple (x,y)\n x,y co-ordinates of the pointing centre\n (NB uses zero-based indexing a'la numpy)\n " radius_map = _pixel_radius_map(array_shape, pointing_centre) correction_map = pixel_radius_correction(radius_map) return correction_map
Args ---- curve: function f(r) mapping radius *in pixels* from centre -> pb. corr. value. shape: numpy.ndarray.shape Shape of the numpy array to generate (2D) pointing_centre: tuple (x,y) x,y co-ordinates of the pointing centre (NB uses zero-based indexing a'la numpy)
chimenea/pbcor.py
_correction_map
timstaley/chimenea
1
python
def _correction_map(pixel_radius_correction, array_shape, pointing_centre): "\n Args\n ----\n curve: function f(r)\n mapping radius *in pixels* from centre -> pb. corr. value.\n shape: numpy.ndarray.shape\n Shape of the numpy array to generate (2D)\n pointing_centre: tuple (x,y)\n x,y co-ordinates of the pointing centre\n (NB uses zero-based indexing a'la numpy)\n " radius_map = _pixel_radius_map(array_shape, pointing_centre) correction_map = pixel_radius_correction(radius_map) return correction_map
def _correction_map(pixel_radius_correction, array_shape, pointing_centre): "\n Args\n ----\n curve: function f(r)\n mapping radius *in pixels* from centre -> pb. corr. value.\n shape: numpy.ndarray.shape\n Shape of the numpy array to generate (2D)\n pointing_centre: tuple (x,y)\n x,y co-ordinates of the pointing centre\n (NB uses zero-based indexing a'la numpy)\n " radius_map = _pixel_radius_map(array_shape, pointing_centre) correction_map = pixel_radius_correction(radius_map) return correction_map<|docstring|>Args ---- curve: function f(r) mapping radius *in pixels* from centre -> pb. corr. value. shape: numpy.ndarray.shape Shape of the numpy array to generate (2D) pointing_centre: tuple (x,y) x,y co-ordinates of the pointing centre (NB uses zero-based indexing a'la numpy)<|endoftext|>
caed340c709f470259f4e82e668111b5b956ea3e07df19c39ed0d56dbf1072c1
def generate_primary_beam_response_map(flux_map_path, pb_sensitivity_curve, cutoff_radius): "\n Generates a primary-beam response map.\n\n Args:\n flux_map: Path to the (inaccurate) default CASA-generated flux map.\n pb_sensitivity_curve: Primary beam sensitivity as a function of radius\n in units of image pixels. (Should be 1.0 at the exact centre).\n cutoff_radius: Radius at which to mask the output image (avoids\n extremely high corrected values for noise fluctuations at large\n radii). Units: image pixels.\n Returns:\n pbmap (pyrap.images.image): Pyrap image object containing the 'flux'\n map (i.e. primary beam response values).\n " logger.debug('Correcting PB map at {}'.format(flux_map_path)) img = pyrap.images.image(flux_map_path) pix_array = img.getdata() rawshape = pix_array.shape pix_array = pix_array.squeeze() centre = _central_position(pix_array.shape) pbmap = _correction_map(pb_sensitivity_curve, pix_array.shape, centre) img.putdata(pbmap.reshape(rawshape)) mask = make_mask(pix_array.shape, centre, cutoff_radius) pbmap = np.ma.array(data=pbmap, mask=mask) img.putmask(mask.reshape(rawshape)) return pbmap
Generates a primary-beam response map. Args: flux_map: Path to the (inaccurate) default CASA-generated flux map. pb_sensitivity_curve: Primary beam sensitivity as a function of radius in units of image pixels. (Should be 1.0 at the exact centre). cutoff_radius: Radius at which to mask the output image (avoids extremely high corrected values for noise fluctuations at large radii). Units: image pixels. Returns: pbmap (pyrap.images.image): Pyrap image object containing the 'flux' map (i.e. primary beam response values).
chimenea/pbcor.py
generate_primary_beam_response_map
timstaley/chimenea
1
python
def generate_primary_beam_response_map(flux_map_path, pb_sensitivity_curve, cutoff_radius): "\n Generates a primary-beam response map.\n\n Args:\n flux_map: Path to the (inaccurate) default CASA-generated flux map.\n pb_sensitivity_curve: Primary beam sensitivity as a function of radius\n in units of image pixels. (Should be 1.0 at the exact centre).\n cutoff_radius: Radius at which to mask the output image (avoids\n extremely high corrected values for noise fluctuations at large\n radii). Units: image pixels.\n Returns:\n pbmap (pyrap.images.image): Pyrap image object containing the 'flux'\n map (i.e. primary beam response values).\n " logger.debug('Correcting PB map at {}'.format(flux_map_path)) img = pyrap.images.image(flux_map_path) pix_array = img.getdata() rawshape = pix_array.shape pix_array = pix_array.squeeze() centre = _central_position(pix_array.shape) pbmap = _correction_map(pb_sensitivity_curve, pix_array.shape, centre) img.putdata(pbmap.reshape(rawshape)) mask = make_mask(pix_array.shape, centre, cutoff_radius) pbmap = np.ma.array(data=pbmap, mask=mask) img.putmask(mask.reshape(rawshape)) return pbmap
def generate_primary_beam_response_map(flux_map_path, pb_sensitivity_curve, cutoff_radius): "\n Generates a primary-beam response map.\n\n Args:\n flux_map: Path to the (inaccurate) default CASA-generated flux map.\n pb_sensitivity_curve: Primary beam sensitivity as a function of radius\n in units of image pixels. (Should be 1.0 at the exact centre).\n cutoff_radius: Radius at which to mask the output image (avoids\n extremely high corrected values for noise fluctuations at large\n radii). Units: image pixels.\n Returns:\n pbmap (pyrap.images.image): Pyrap image object containing the 'flux'\n map (i.e. primary beam response values).\n " logger.debug('Correcting PB map at {}'.format(flux_map_path)) img = pyrap.images.image(flux_map_path) pix_array = img.getdata() rawshape = pix_array.shape pix_array = pix_array.squeeze() centre = _central_position(pix_array.shape) pbmap = _correction_map(pb_sensitivity_curve, pix_array.shape, centre) img.putdata(pbmap.reshape(rawshape)) mask = make_mask(pix_array.shape, centre, cutoff_radius) pbmap = np.ma.array(data=pbmap, mask=mask) img.putmask(mask.reshape(rawshape)) return pbmap<|docstring|>Generates a primary-beam response map. Args: flux_map: Path to the (inaccurate) default CASA-generated flux map. pb_sensitivity_curve: Primary beam sensitivity as a function of radius in units of image pixels. (Should be 1.0 at the exact centre). cutoff_radius: Radius at which to mask the output image (avoids extremely high corrected values for noise fluctuations at large radii). Units: image pixels. Returns: pbmap (pyrap.images.image): Pyrap image object containing the 'flux' map (i.e. primary beam response values).<|endoftext|>
e183289c9ae9937c9285d0529e4a0b7e8c55b113a9937a676b9a142582d3855e
def apply_pb_correction(obs, pb_sensitivity_curve, cutoff_radius): '\n Updates the primary beam response maps for cleaned images in an ObsInfo object.\n\n Args:\n obs (ObsInfo): Observation to generate maps for.\n pb_sensitivity_curve: Primary beam sensitivity as a function of radius\n in units of image pixels. (Should be 1.0 at the exact centre).\n cutoff_radius: Radius at which to mask the output image (avoids\n extremely high corrected values for noise fluctuations at large\n radii). Units: image pixels.\n ' assert isinstance(obs, ObsInfo) def update_pb_map_for_img(flux_map_path): pbmap = generate_primary_beam_response_map(flux_map_path, pb_sensitivity_curve, cutoff_radius) return pbmap def process_clean_maps(clean_maps): pbmap = update_pb_map_for_img(clean_maps.flux) img_path = clean_maps.image pb_img_path = (img_path + '.pbcor') generate_pb_corrected_image(img_path, pb_img_path, pbmap) clean_maps.pbcor = pb_img_path if obs.maps_masked.ms.image: process_clean_maps(obs.maps_masked.ms) if obs.maps_open.ms.image: process_clean_maps(obs.maps_open.ms) if obs.maps_hybrid.ms.image: process_clean_maps(obs.maps_hybrid.ms)
Updates the primary beam response maps for cleaned images in an ObsInfo object. Args: obs (ObsInfo): Observation to generate maps for. pb_sensitivity_curve: Primary beam sensitivity as a function of radius in units of image pixels. (Should be 1.0 at the exact centre). cutoff_radius: Radius at which to mask the output image (avoids extremely high corrected values for noise fluctuations at large radii). Units: image pixels.
chimenea/pbcor.py
apply_pb_correction
timstaley/chimenea
1
python
def apply_pb_correction(obs, pb_sensitivity_curve, cutoff_radius): '\n Updates the primary beam response maps for cleaned images in an ObsInfo object.\n\n Args:\n obs (ObsInfo): Observation to generate maps for.\n pb_sensitivity_curve: Primary beam sensitivity as a function of radius\n in units of image pixels. (Should be 1.0 at the exact centre).\n cutoff_radius: Radius at which to mask the output image (avoids\n extremely high corrected values for noise fluctuations at large\n radii). Units: image pixels.\n ' assert isinstance(obs, ObsInfo) def update_pb_map_for_img(flux_map_path): pbmap = generate_primary_beam_response_map(flux_map_path, pb_sensitivity_curve, cutoff_radius) return pbmap def process_clean_maps(clean_maps): pbmap = update_pb_map_for_img(clean_maps.flux) img_path = clean_maps.image pb_img_path = (img_path + '.pbcor') generate_pb_corrected_image(img_path, pb_img_path, pbmap) clean_maps.pbcor = pb_img_path if obs.maps_masked.ms.image: process_clean_maps(obs.maps_masked.ms) if obs.maps_open.ms.image: process_clean_maps(obs.maps_open.ms) if obs.maps_hybrid.ms.image: process_clean_maps(obs.maps_hybrid.ms)
def apply_pb_correction(obs, pb_sensitivity_curve, cutoff_radius): '\n Updates the primary beam response maps for cleaned images in an ObsInfo object.\n\n Args:\n obs (ObsInfo): Observation to generate maps for.\n pb_sensitivity_curve: Primary beam sensitivity as a function of radius\n in units of image pixels. (Should be 1.0 at the exact centre).\n cutoff_radius: Radius at which to mask the output image (avoids\n extremely high corrected values for noise fluctuations at large\n radii). Units: image pixels.\n ' assert isinstance(obs, ObsInfo) def update_pb_map_for_img(flux_map_path): pbmap = generate_primary_beam_response_map(flux_map_path, pb_sensitivity_curve, cutoff_radius) return pbmap def process_clean_maps(clean_maps): pbmap = update_pb_map_for_img(clean_maps.flux) img_path = clean_maps.image pb_img_path = (img_path + '.pbcor') generate_pb_corrected_image(img_path, pb_img_path, pbmap) clean_maps.pbcor = pb_img_path if obs.maps_masked.ms.image: process_clean_maps(obs.maps_masked.ms) if obs.maps_open.ms.image: process_clean_maps(obs.maps_open.ms) if obs.maps_hybrid.ms.image: process_clean_maps(obs.maps_hybrid.ms)<|docstring|>Updates the primary beam response maps for cleaned images in an ObsInfo object. Args: obs (ObsInfo): Observation to generate maps for. pb_sensitivity_curve: Primary beam sensitivity as a function of radius in units of image pixels. (Should be 1.0 at the exact centre). cutoff_radius: Radius at which to mask the output image (avoids extremely high corrected values for noise fluctuations at large radii). Units: image pixels.<|endoftext|>
7e418c17f62f6c32b5ec6d8707770f9c9cbaf283e1eb9487b46bb170205f5331
async def quick_death_lifecycle(task: fake_singularity.Task) -> None: 'Task dies instantly' task.state = fake_singularity.TaskState.DEAD
Task dies instantly
katsdpcontroller/test/test_master_controller.py
quick_death_lifecycle
ska-sa/katsdpcontroller
0
python
async def quick_death_lifecycle(task: fake_singularity.Task) -> None: task.state = fake_singularity.TaskState.DEAD
async def quick_death_lifecycle(task: fake_singularity.Task) -> None: task.state = fake_singularity.TaskState.DEAD<|docstring|>Task dies instantly<|endoftext|>
8ed5daac98811355a4c840b9a2689bc8fc972d1418b7055d0167c8f4466ac2bf
async def death_after_task_id_lifecycle(init_wait: float, task: fake_singularity.Task) -> None: 'Task dies as soon as the client sees the task ID.' (await asyncio.sleep(init_wait)) task.state = fake_singularity.TaskState.NOT_YET_HEALTHY (await task.task_id_known.wait()) task.state = fake_singularity.TaskState.DEAD
Task dies as soon as the client sees the task ID.
katsdpcontroller/test/test_master_controller.py
death_after_task_id_lifecycle
ska-sa/katsdpcontroller
0
python
async def death_after_task_id_lifecycle(init_wait: float, task: fake_singularity.Task) -> None: (await asyncio.sleep(init_wait)) task.state = fake_singularity.TaskState.NOT_YET_HEALTHY (await task.task_id_known.wait()) task.state = fake_singularity.TaskState.DEAD
async def death_after_task_id_lifecycle(init_wait: float, task: fake_singularity.Task) -> None: (await asyncio.sleep(init_wait)) task.state = fake_singularity.TaskState.NOT_YET_HEALTHY (await task.task_id_known.wait()) task.state = fake_singularity.TaskState.DEAD<|docstring|>Task dies as soon as the client sees the task ID.<|endoftext|>
5489fe6fadea252a441d31526cd2659a5ac64bc5c2e3b360080798b6b501cf16
async def spontaneous_death_lifecycle(task: fake_singularity.Task) -> None: 'Task dies after 1000s of life' (await fake_singularity.default_lifecycle(task, times={fake_singularity.TaskState.HEALTHY: 1000.0}))
Task dies after 1000s of life
katsdpcontroller/test/test_master_controller.py
spontaneous_death_lifecycle
ska-sa/katsdpcontroller
0
python
async def spontaneous_death_lifecycle(task: fake_singularity.Task) -> None: (await fake_singularity.default_lifecycle(task, times={fake_singularity.TaskState.HEALTHY: 1000.0}))
async def spontaneous_death_lifecycle(task: fake_singularity.Task) -> None: (await fake_singularity.default_lifecycle(task, times={fake_singularity.TaskState.HEALTHY: 1000.0}))<|docstring|>Task dies after 1000s of life<|endoftext|>
06fb279767053c7c5b941940de575a993bec27a50167497eb4d20510ca3768ee
async def long_pending_lifecycle(task: fake_singularity.Task) -> None: 'Task takes longer than the timeout to make it out of pending state' (await fake_singularity.default_lifecycle(task, times={fake_singularity.TaskState.PENDING: 1000.0}))
Task takes longer than the timeout to make it out of pending state
katsdpcontroller/test/test_master_controller.py
long_pending_lifecycle
ska-sa/katsdpcontroller
0
python
async def long_pending_lifecycle(task: fake_singularity.Task) -> None: (await fake_singularity.default_lifecycle(task, times={fake_singularity.TaskState.PENDING: 1000.0}))
async def long_pending_lifecycle(task: fake_singularity.Task) -> None: (await fake_singularity.default_lifecycle(task, times={fake_singularity.TaskState.PENDING: 1000.0}))<|docstring|>Task takes longer than the timeout to make it out of pending state<|endoftext|>
9a6eee0fe4c831030db2834146a2f16ee9a2785a5b838084a7a64a87a17fd8c6
async def katcp_server_lifecycle(task: fake_singularity.Task) -> None: 'The default lifecycle, but creates a real katcp port' server = DummyProductController('127.0.0.1', 0) (await server.start()) try: (task.host, task.ports[0]) = device_server_sockname(server) (await fake_singularity.default_lifecycle(task)) finally: (await server.stop())
The default lifecycle, but creates a real katcp port
katsdpcontroller/test/test_master_controller.py
katcp_server_lifecycle
ska-sa/katsdpcontroller
0
python
async def katcp_server_lifecycle(task: fake_singularity.Task) -> None: server = DummyProductController('127.0.0.1', 0) (await server.start()) try: (task.host, task.ports[0]) = device_server_sockname(server) (await fake_singularity.default_lifecycle(task)) finally: (await server.stop())
async def katcp_server_lifecycle(task: fake_singularity.Task) -> None: server = DummyProductController('127.0.0.1', 0) (await server.start()) try: (task.host, task.ports[0]) = device_server_sockname(server) (await fake_singularity.default_lifecycle(task)) finally: (await server.stop())<|docstring|>The default lifecycle, but creates a real katcp port<|endoftext|>
790897a1eac396534aa6065fe25f15e2701decbe264f500fc7cede3045abd45a
async def request_capture_status(self, ctx: aiokatcp.RequestContext) -> str: 'Get product status' return 'idle'
Get product status
katsdpcontroller/test/test_master_controller.py
request_capture_status
ska-sa/katsdpcontroller
0
python
async def request_capture_status(self, ctx: aiokatcp.RequestContext) -> str: return 'idle'
async def request_capture_status(self, ctx: aiokatcp.RequestContext) -> str: return 'idle'<|docstring|>Get product status<|endoftext|>
c0a078567a14118bd05e544ab9b0acd0defb113847bc3f24b78c75c0ea2d4bb1
async def request_telstate_endpoint(self, ctx: aiokatcp.RequestContext) -> str: 'Get the telescope state endpoint' return 'telstate.invalid:31000'
Get the telescope state endpoint
katsdpcontroller/test/test_master_controller.py
request_telstate_endpoint
ska-sa/katsdpcontroller
0
python
async def request_telstate_endpoint(self, ctx: aiokatcp.RequestContext) -> str: return 'telstate.invalid:31000'
async def request_telstate_endpoint(self, ctx: aiokatcp.RequestContext) -> str: return 'telstate.invalid:31000'<|docstring|>Get the telescope state endpoint<|endoftext|>
680322294b9c04a76952d8c48fda827dcf67b9bfdf4e033b73ae77cd71061b29
async def start_manager(self) -> None: 'Start the manager and arrange for it to be stopped' (await self.manager.start()) self.addCleanup(self.stop_manager)
Start the manager and arrange for it to be stopped
katsdpcontroller/test/test_master_controller.py
start_manager
ska-sa/katsdpcontroller
0
python
async def start_manager(self) -> None: (await self.manager.start()) self.addCleanup(self.stop_manager)
async def start_manager(self) -> None: (await self.manager.start()) self.addCleanup(self.stop_manager)<|docstring|>Start the manager and arrange for it to be stopped<|endoftext|>
5640504583c6320f0c507df5648bc34abab22c1b99375a4ce53ef6fb402e0d80
async def stop_manager(self) -> None: 'Stop the manager.\n\n This is used as a cleanup function rather than ``self.manager.stop``\n directly, because it binds to the manager set at the time of call\n whereas ``self.manager.stop`` binds immediately.\n ' (await self.manager.stop())
Stop the manager. This is used as a cleanup function rather than ``self.manager.stop`` directly, because it binds to the manager set at the time of call whereas ``self.manager.stop`` binds immediately.
katsdpcontroller/test/test_master_controller.py
stop_manager
ska-sa/katsdpcontroller
0
python
async def stop_manager(self) -> None: 'Stop the manager.\n\n This is used as a cleanup function rather than ``self.manager.stop``\n directly, because it binds to the manager set at the time of call\n whereas ``self.manager.stop`` binds immediately.\n ' (await self.manager.stop())
async def stop_manager(self) -> None: 'Stop the manager.\n\n This is used as a cleanup function rather than ``self.manager.stop``\n directly, because it binds to the manager set at the time of call\n whereas ``self.manager.stop`` binds immediately.\n ' (await self.manager.stop())<|docstring|>Stop the manager. This is used as a cleanup function rather than ``self.manager.stop`` directly, because it binds to the manager set at the time of call whereas ``self.manager.stop`` binds immediately.<|endoftext|>