uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
92fce53fbae6e25f62249ccf | train | function | def test_load_dll_using_ctypes(monkeypatch, pyi_builder, compiled_dylib):
# Note that including the data_dir fixture copies files needed by this test.
#
# TODO Make sure PyInstaller is able to find the library and bundle it with the app.
# # If the required dylib does not reside in the current directory... | def test_load_dll_using_ctypes(monkeypatch, pyi_builder, compiled_dylib):
# Note that including the data_dir fixture copies files needed by this test.
#
# TODO Make sure PyInstaller is able to find the library and bundle it with the app.
# # If the required dylib does not reside in the current directory... | pyi_builder.test_script('pyi_load_dll_using_ctypes.py')
| def test_load_dll_using_ctypes(monkeypatch, pyi_builder, compiled_dylib):
# Note that including the data_dir fixture copies files needed by this test.
#
# TODO Make sure PyInstaller is able to find the library and bundle it with the app.
# # If the required dylib does not reside in the current directory... | 212 | 68 | 229 | 212 | 0 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_load_dll_using_ctypes | test_load_dll_using_ctypes | 130 | 146 | 130 | 145 | e2ba5f7ddabf1375395c675bf0f0cf92d96d8e83 | bigcode/the-stack | train |
f027ac2e043e8dacfecc593b | train | function | def test_chdir_meipass(pyi_builder):
pyi_builder.test_script('pyi_chdir_meipass.py')
| def test_chdir_meipass(pyi_builder):
| pyi_builder.test_script('pyi_chdir_meipass.py')
|
# Build and run the app.
pyi_builder.test_script('pyi_load_dll_using_ctypes.py')
def test_get_meipass_value(pyi_builder):
pyi_builder.test_script('pyi_get_meipass_value.py')
def test_chdir_meipass(pyi_builder):
| 64 | 64 | 27 | 11 | 53 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_chdir_meipass | test_chdir_meipass | 153 | 154 | 153 | 153 | 69228acfebee0f332976529d3021468a303a07b8 | bigcode/the-stack | train |
f1d1f1a5600ce814a8168457 | train | function | @importorskip('win32com')
def test_pywin32_win32com(pyi_builder):
pyi_builder.test_script('pyi_pywin32_win32com.py')
| @importorskip('win32com')
def test_pywin32_win32com(pyi_builder):
| pyi_builder.test_script('pyi_pywin32_win32com.py')
| yi_builder):
pyi_builder.test_script('pyi_threading_module.py')
def test_argument(pyi_builder):
pyi_builder.test_script('pyi_argument.py', app_args=["--argument"])
@importorskip('win32com')
def test_pywin32_win32com(pyi_builder):
| 63 | 64 | 38 | 21 | 42 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_pywin32_win32com | test_pywin32_win32com | 264 | 266 | 264 | 265 | c98f643375d485e7950e9fdd9fcee8509ebe2c40 | bigcode/the-stack | train |
07a27663022a8f8ba66b1d48 | train | function | def test_argument(pyi_builder):
pyi_builder.test_script('pyi_argument.py', app_args=["--argument"])
| def test_argument(pyi_builder):
| pyi_builder.test_script('pyi_argument.py', app_args=["--argument"])
| ('pyi_time_module.py')
def test_xmldom_module(pyi_builder):
pyi_builder.test_script('pyi_xmldom_module.py')
def test_threading_module(pyi_builder):
pyi_builder.test_script('pyi_threading_module.py')
def test_argument(pyi_builder):
| 64 | 64 | 25 | 7 | 57 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_argument | test_argument | 260 | 261 | 260 | 260 | 34bee37ce6df286bb89f1f9b03ef21df16ff25d9 | bigcode/the-stack | train |
e91e53f5a8f54cb36be2396e | train | function | @importorskip('codecs')
def test_codecs(pyi_builder):
pyi_builder.test_script('pyi_codecs.py')
| @importorskip('codecs')
def test_codecs(pyi_builder):
| pyi_builder.test_script('pyi_codecs.py')
| .py')
def test_absolute_python_path(pyi_builder):
pyi_builder.test_script('pyi_absolute_python_path.py')
def test_celementtree(pyi_builder):
pyi_builder.test_script('pyi_celementtree.py')
@importorskip('codecs')
def test_codecs(pyi_builder):
| 64 | 64 | 29 | 16 | 48 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_codecs | test_codecs | 48 | 50 | 48 | 49 | 57f56d5671a1f5129b6d932c650f46dad6b4e36d | bigcode/the-stack | train |
2acf254283a8d8d9fad41235 | train | function | @skipif_notosx
def test_osx_override_info_plist(pyi_builder_spec):
pyi_builder_spec.test_spec('pyi_osx_override_info_plist.spec')
| @skipif_notosx
def test_osx_override_info_plist(pyi_builder_spec):
| pyi_builder_spec.test_spec('pyi_osx_override_info_plist.spec')
| )
newexes.append(new)
return newexes
pyi_builder._find_executables = _find_executables
pyi_builder.test_script('pyi_helloworld.py')
@skipif_notosx
def test_osx_override_info_plist(pyi_builder_spec):
| 64 | 64 | 38 | 20 | 44 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_osx_override_info_plist | test_osx_override_info_plist | 291 | 293 | 291 | 292 | 942a7421a08f30225100d8cccf6cc93b85f723c4 | bigcode/the-stack | train |
d5f718b82c76079eeb9a00b9 | train | function | @importorskip('multiprocessing')
def test_multiprocess_pool(pyi_builder):
pyi_builder.test_script('pyi_multiprocess_pool.py')
| @importorskip('multiprocessing')
def test_multiprocess_pool(pyi_builder):
| pyi_builder.test_script('pyi_multiprocess_pool.py')
| _script('pyi_multiprocess.py')
@importorskip('multiprocessing')
def test_multiprocess_forking(pyi_builder):
pyi_builder.test_script('pyi_multiprocess_forking.py')
@importorskip('multiprocessing')
def test_multiprocess_pool(pyi_builder):
| 64 | 64 | 33 | 18 | 46 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_multiprocess_pool | test_multiprocess_pool | 123 | 125 | 123 | 124 | 53328d8973d4d2eb96521bffd1d0eb453f86ca6c | bigcode/the-stack | train |
42a63d444b97b092aeee7361 | train | function | @importorskip('multiprocessing')
def test_multiprocess(pyi_builder):
pyi_builder.test_script('pyi_multiprocess.py')
| @importorskip('multiprocessing')
def test_multiprocess(pyi_builder):
| pyi_builder.test_script('pyi_multiprocess.py')
| .test_script('pyi_module_attributes.py')
def test_module_reload(pyi_builder):
pyi_builder.test_script('pyi_module_reload.py')
# TODO move 'multiprocessig' tests into 'test_multiprocess.py.
@importorskip('multiprocessing')
def test_multiprocess(pyi_builder):
| 64 | 64 | 31 | 17 | 47 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_multiprocess | test_multiprocess | 113 | 115 | 113 | 114 | 4b570c16d89546f66ebb7e3528821c43d7f04815 | bigcode/the-stack | train |
bd20d1e15331721ed25705e3 | train | function | @importorskip('multiprocessing')
def test_multiprocess_forking(pyi_builder):
pyi_builder.test_script('pyi_multiprocess_forking.py')
| @importorskip('multiprocessing')
def test_multiprocess_forking(pyi_builder):
| pyi_builder.test_script('pyi_multiprocess_forking.py')
| multiprocessig' tests into 'test_multiprocess.py.
@importorskip('multiprocessing')
def test_multiprocess(pyi_builder):
pyi_builder.test_script('pyi_multiprocess.py')
@importorskip('multiprocessing')
def test_multiprocess_forking(pyi_builder):
| 64 | 64 | 37 | 20 | 44 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_multiprocess_forking | test_multiprocess_forking | 118 | 120 | 118 | 119 | 2fdb31bad299907ce4e36d6da2b60e832a6edaba | bigcode/the-stack | train |
5ef7b4b8fe1d5168682b5bd0 | train | function | def test_stdout_encoding(tmpdir, pyi_builder):
with open(os.path.join(tmpdir.strpath, 'stdout_encoding.build'), 'w') as f:
if is_py2:
if sys.stdout.isatty() and is_win:
enc = str(sys.stdout.encoding)
else:
# In Python 2 on Mac OS X and Linux 'sys.stdou... | def test_stdout_encoding(tmpdir, pyi_builder):
| with open(os.path.join(tmpdir.strpath, 'stdout_encoding.build'), 'w') as f:
if is_py2:
if sys.stdout.isatty() and is_win:
enc = str(sys.stdout.encoding)
else:
# In Python 2 on Mac OS X and Linux 'sys.stdout.encoding' is set to None.
# O... | active stderr use locale encoding - ANSI codepage.
# This fixes the test when running with py.test and capturing output.
enc = locale.getpreferredencoding(False)
f.write(enc)
pyi_builder.test_script('pyi_stderr_encoding.py')
def test_stdout_encoding(tmpdir, pyi_builder):
| 64 | 64 | 181 | 11 | 53 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_stdout_encoding | test_stdout_encoding | 213 | 229 | 213 | 213 | 4b2c27efac0fc6ace3b39399298475cd52835a6d | bigcode/the-stack | train |
b5d950be68dcf132d3d381d7 | train | function | def test_decoders_ascii(pyi_builder):
pyi_builder.test_script('pyi_decoders_ascii.py')
| def test_decoders_ascii(pyi_builder):
| pyi_builder.test_script('pyi_decoders_ascii.py')
| _path.py')
def test_celementtree(pyi_builder):
pyi_builder.test_script('pyi_celementtree.py')
@importorskip('codecs')
def test_codecs(pyi_builder):
pyi_builder.test_script('pyi_codecs.py')
def test_decoders_ascii(pyi_builder):
| 64 | 64 | 23 | 9 | 55 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_decoders_ascii | test_decoders_ascii | 53 | 54 | 53 | 53 | 9de99c9989e886c82a382f4ccd79549b4190fb02 | bigcode/the-stack | train |
f5fb25f3d77c61bfbbe422fe | train | function | def test_helloworld(pyi_builder):
pyi_builder.test_script('pyi_helloworld.py')
| def test_helloworld(pyi_builder):
| pyi_builder.test_script('pyi_helloworld.py')
| yi_builder.test_script('pyi_feature_nocrypto.py')
def test_filename(pyi_builder):
pyi_builder.test_script('pyi_filename.py')
def test_getfilesystemencoding(pyi_builder):
pyi_builder.test_script('pyi_getfilesystemencoding.py')
def test_helloworld(pyi_builder):
| 64 | 64 | 23 | 9 | 55 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_helloworld | test_helloworld | 86 | 87 | 86 | 86 | 11f41e93c350ced1e86f5ac23b50cd1c6b29a690 | bigcode/the-stack | train |
19d369eb1694889f91a04016 | train | function | @skipif_winorosx
def test_absolute_ld_library_path(pyi_builder):
pyi_builder.test_script('pyi_absolute_ld_library_path.py')
| @skipif_winorosx
def test_absolute_ld_library_path(pyi_builder):
| pyi_builder.test_script('pyi_absolute_ld_library_path.py')
| _winorosx, \
skipif_notwin, skipif_notosx
def test_run_from_path_environ(pyi_builder):
pyi_builder.test_script('pyi_absolute_python_path.py', run_from_path=True)
@skipif_winorosx
def test_absolute_ld_library_path(pyi_builder):
| 64 | 64 | 32 | 17 | 47 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_absolute_ld_library_path | test_absolute_ld_library_path | 35 | 37 | 35 | 36 | 2c67c5aef846457afc8bf1d0817ed48418d67571 | bigcode/the-stack | train |
2ff8056f91c3bc5a44946589 | train | function | def test_email(pyi_builder):
pyi_builder.test_script('pyi_email.py')
| def test_email(pyi_builder):
| pyi_builder.test_script('pyi_email.py')
| _builder.test_script('pyi_decoders_ascii.py')
def test_distutils_submod(pyi_builder):
pyi_builder.test_script('pyi_distutils_submod.py')
def test_dynamic_module(pyi_builder):
pyi_builder.test_script('pyi_dynamic_module.py')
def test_email(pyi_builder):
| 64 | 64 | 19 | 7 | 57 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_email | test_email | 65 | 66 | 65 | 65 | dde6aac8ae3237cda1e5c0f30697378f959c8c0a | bigcode/the-stack | train |
06ab1ec7b44bf3bae65d9b17 | train | function | def test_stderr_encoding(tmpdir, pyi_builder):
# NOTE: '-s' option to pytest disables output capturing, changing this test's result:
# without -s: py.test process changes its own stdout encoding to 'UTF-8' to
# capture output. subprocess spawned by py.test has stdout encoding
# '... | def test_stderr_encoding(tmpdir, pyi_builder):
# NOTE: '-s' option to pytest disables output capturing, changing this test's result:
# without -s: py.test process changes its own stdout encoding to 'UTF-8' to
# capture output. subprocess spawned by py.test has stdout encoding
# '... | with open(os.path.join(tmpdir.strpath, 'stderr_encoding.build'), 'w') as f:
if is_py2:
if sys.stderr.isatty() and is_win:
enc = str(sys.stderr.encoding)
else:
# In Python 2 on Mac OS X and Linux 'sys.stderr.encoding' is set to None.
# O... | def test_stderr_encoding(tmpdir, pyi_builder):
# NOTE: '-s' option to pytest disables output capturing, changing this test's result:
# without -s: py.test process changes its own stdout encoding to 'UTF-8' to
# capture output. subprocess spawned by py.test has stdout encoding
# '... | 132 | 90 | 303 | 132 | 0 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_stderr_encoding | test_stderr_encoding | 187 | 210 | 187 | 194 | 22331b823cda650a91ee9ded726d395361ee8dde | bigcode/the-stack | train |
ae626971151974cffc808b7f | train | function | @skipif_win
def test_python_makefile(pyi_builder):
pyi_builder.test_script('pyi_python_makefile.py')
| @skipif_win
def test_python_makefile(pyi_builder):
| pyi_builder.test_script('pyi_python_makefile.py')
| option --exclude-module=xml.sax
the module 'xml.sax' won't be bundled.
"""
pyi_builder.test_script('pyi_option_exclude_module.py',
pyi_args=['--exclude-module', 'xml.sax'])
@skipif_win
def test_python_makefile(pyi_builder):
| 63 | 64 | 28 | 14 | 49 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_python_makefile | test_python_makefile | 166 | 168 | 166 | 167 | 205268f97bc0515c42487ec408b4b0c602fed1b7 | bigcode/the-stack | train |
b09e28fd0ce4b4d2753885d1 | train | function | def test_python_home(pyi_builder):
pyi_builder.test_script('pyi_python_home.py')
| def test_python_home(pyi_builder):
| pyi_builder.test_script('pyi_python_home.py')
| .strpath, 'pyi_icon.icns')]
else:
pytest.skip('option --icon works only on Windows and Mac OS X')
# Just use helloworld script.
pyi_builder.test_script('pyi_helloworld.py', pyi_args=args)
def test_python_home(pyi_builder):
| 64 | 64 | 21 | 8 | 56 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_python_home | test_python_home | 183 | 184 | 183 | 183 | da6413ddb2b9266bea0504e8eec5279e2eac3b33 | bigcode/the-stack | train |
236530a0e181f319fd676809 | train | function | def test_threading_module(pyi_builder):
pyi_builder.test_script('pyi_threading_module.py')
| def test_threading_module(pyi_builder):
| pyi_builder.test_script('pyi_threading_module.py')
| .UTF-8'
monkeypatch.setenv('LC_ALL', lang)
pyi_builder.test_script('pyi_time_module.py')
def test_xmldom_module(pyi_builder):
pyi_builder.test_script('pyi_xmldom_module.py')
def test_threading_module(pyi_builder):
| 64 | 64 | 23 | 9 | 55 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_threading_module | test_threading_module | 256 | 257 | 256 | 256 | a0c34373a203a3c6e9c9e86840ac280e3cc2203c | bigcode/the-stack | train |
ceea6fe721dcbfa030f9811d | train | function | def test_celementtree(pyi_builder):
pyi_builder.test_script('pyi_celementtree.py')
| def test_celementtree(pyi_builder):
| pyi_builder.test_script('pyi_celementtree.py')
| @skipif_winorosx
def test_absolute_ld_library_path(pyi_builder):
pyi_builder.test_script('pyi_absolute_ld_library_path.py')
def test_absolute_python_path(pyi_builder):
pyi_builder.test_script('pyi_absolute_python_path.py')
def test_celementtree(pyi_builder):
| 64 | 64 | 23 | 9 | 55 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_celementtree | test_celementtree | 44 | 45 | 44 | 44 | 3e684e9067551ce4ebc30e7ecc5bd608fcd91760 | bigcode/the-stack | train |
d7886e847516d39155cd9741 | train | function | def test_getfilesystemencoding(pyi_builder):
pyi_builder.test_script('pyi_getfilesystemencoding.py')
| def test_getfilesystemencoding(pyi_builder):
| pyi_builder.test_script('pyi_getfilesystemencoding.py')
| ', pyi_args=['--key=test_key'])
def test_feature_nocrypto(pyi_builder):
pyi_builder.test_script('pyi_feature_nocrypto.py')
def test_filename(pyi_builder):
pyi_builder.test_script('pyi_filename.py')
def test_getfilesystemencoding(pyi_builder):
| 64 | 64 | 23 | 9 | 55 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_getfilesystemencoding | test_getfilesystemencoding | 82 | 83 | 82 | 82 | 0a8719adc949a5a66a738568c7c41c7f029c8841 | bigcode/the-stack | train |
e522e0080b2e9ffbfa9565b2 | train | function | @skipif_win
def test_time_module_localized(pyi_builder, monkeypatch):
# This checks that functions 'time.ctime()' and 'time.strptime()'
# use the same locale. There was an issue with bootloader where
# every function was using different locale:
# time.ctime was using 'C'
# time.strptime was using 'x... | @skipif_win
def test_time_module_localized(pyi_builder, monkeypatch):
# This checks that functions 'time.ctime()' and 'time.strptime()'
# use the same locale. There was an issue with bootloader where
# every function was using different locale:
# time.ctime was using 'C'
# time.strptime was using 'x... | lang = 'cs_CZ' if is_darwin else 'cs_CZ.UTF-8'
monkeypatch.setenv('LC_ALL', lang)
pyi_builder.test_script('pyi_time_module.py')
| @skipif_win
def test_time_module_localized(pyi_builder, monkeypatch):
# This checks that functions 'time.ctime()' and 'time.strptime()'
# use the same locale. There was an issue with bootloader where
# every function was using different locale:
# time.ctime was using 'C'
# time.strptime was using 'x... | 86 | 64 | 132 | 86 | 0 | dvt32/mypymodoro | resources/PyInstaller-3.0/tests/functional/test_basic.py | Python | test_time_module_localized | test_time_module_localized | 240 | 249 | 240 | 246 | 36adb161ed181e5689408cd2e2e454647b44f1b6 | bigcode/the-stack | train |
a461ffb631d49970241f8f1a | train | class | class ScriptPyTextModule(ScriptModule):
def __init__(
self,
model: torch.jit.ScriptModule,
output_layer: torch.jit.ScriptModule,
tensorizer: ScriptTensorizer,
):
super().__init__()
self.model = model
self.output_layer = output_layer
self.tensorizer... | class ScriptPyTextModule(ScriptModule):
| def __init__(
self,
model: torch.jit.ScriptModule,
output_layer: torch.jit.ScriptModule,
tensorizer: ScriptTensorizer,
):
super().__init__()
self.model = model
self.output_layer = output_layer
self.tensorizer = tensorizer
@torch.jit.script_met... | if texts is not None:
return squeeze_1d(texts)
return multi_texts
class ScriptModule(torch.jit.ScriptModule):
@torch.jit.script_method
def set_device(self, device: str):
self.tensorizer.set_device(device)
class ScriptPyTextModule(ScriptModule):
| 66 | 66 | 221 | 9 | 57 | cakkaya/pytext | pytext/torchscript/module.py | Python | ScriptPyTextModule | ScriptPyTextModule | 26 | 54 | 26 | 26 | 62844183e83b9c8a9df03ec69f1b301c982b9a4c | bigcode/the-stack | train |
c863467e0f38176cfbec763c | train | function | @torch.jit.script
def resolve_texts(
texts: Optional[List[str]] = None, multi_texts: Optional[List[List[str]]] = None
) -> Optional[List[List[str]]]:
if texts is not None:
return squeeze_1d(texts)
return multi_texts
| @torch.jit.script
def resolve_texts(
texts: Optional[List[str]] = None, multi_texts: Optional[List[List[str]]] = None
) -> Optional[List[List[str]]]:
| if texts is not None:
return squeeze_1d(texts)
return multi_texts
|
from pytext.torchscript.utils import ScriptBatchInput, squeeze_1d, squeeze_2d
@torch.jit.script
def resolve_texts(
texts: Optional[List[str]] = None, multi_texts: Optional[List[List[str]]] = None
) -> Optional[List[List[str]]]:
| 64 | 64 | 63 | 41 | 22 | cakkaya/pytext | pytext/torchscript/module.py | Python | resolve_texts | resolve_texts | 11 | 17 | 11 | 14 | 3f876820f640167d7f0c6616680324a40116d823 | bigcode/the-stack | train |
eb627b9d75cce1f74df2d8cb | train | class | class ScriptPyTextEmbeddingModuleIndex(ScriptPyTextEmbeddingModule):
def __init__(
self,
model: torch.jit.ScriptModule,
tensorizer: ScriptTensorizer,
index: int = 0,
):
super().__init__(model, tensorizer)
self.index = torch.jit.Attribute(index, int)
@torch.ji... | class ScriptPyTextEmbeddingModuleIndex(ScriptPyTextEmbeddingModule):
| def __init__(
self,
model: torch.jit.ScriptModule,
tensorizer: ScriptTensorizer,
index: int = 0,
):
super().__init__(model, tensorizer)
self.index = torch.jit.Attribute(index, int)
@torch.jit.script_method
def _forward(self, inputs: ScriptBatchInput):
... | : ScriptBatchInput = ScriptBatchInput(
texts=resolve_texts(texts, multi_texts),
tokens=squeeze_2d(tokens),
languages=squeeze_1d(languages),
)
return self._forward(inputs)
class ScriptPyTextEmbeddingModuleIndex(ScriptPyTextEmbeddingModule):
| 64 | 64 | 114 | 14 | 50 | cakkaya/pytext | pytext/torchscript/module.py | Python | ScriptPyTextEmbeddingModuleIndex | ScriptPyTextEmbeddingModuleIndex | 118 | 131 | 118 | 118 | 3f9b0a3f7c66b337b693e319baeddf881d0f652a | bigcode/the-stack | train |
260a483e2336d827b8d2276a | train | class | class ScriptPyTextEmbeddingModule(ScriptModule):
def __init__(self, model: torch.jit.ScriptModule, tensorizer: ScriptTensorizer):
super().__init__()
self.model = model
self.tensorizer = tensorizer
@torch.jit.script_method
def _forward(self, inputs: ScriptBatchInput):
input_t... | class ScriptPyTextEmbeddingModule(ScriptModule):
| def __init__(self, model: torch.jit.ScriptModule, tensorizer: ScriptTensorizer):
super().__init__()
self.model = model
self.tensorizer = tensorizer
@torch.jit.script_method
def _forward(self, inputs: ScriptBatchInput):
input_tensors = self.tensorizer(inputs)
return s... | languages=squeeze_1d(languages),
)
input_tensors = self.tensorizer(inputs)
dense_feat = self.normalizer.normalize(dense_feat)
logits = self.model(input_tensors, torch.tensor(dense_feat, dtype=torch.float))
return self.output_layer(logits)
class ScriptPyTextEmbeddingModule(Script... | 70 | 70 | 236 | 10 | 60 | cakkaya/pytext | pytext/torchscript/module.py | Python | ScriptPyTextEmbeddingModule | ScriptPyTextEmbeddingModule | 89 | 115 | 89 | 89 | df591c3e701615945fc7fe31bebd9a78e6b62530 | bigcode/the-stack | train |
48834cd8c34eb4787d1a17be | train | class | class ScriptPyTextModuleWithDense(ScriptPyTextModule):
def __init__(
self,
model: torch.jit.ScriptModule,
output_layer: torch.jit.ScriptModule,
tensorizer: ScriptTensorizer,
normalizer: VectorNormalizer,
):
super().__init__(model, output_layer, tensorizer)
... | class ScriptPyTextModuleWithDense(ScriptPyTextModule):
| def __init__(
self,
model: torch.jit.ScriptModule,
output_layer: torch.jit.ScriptModule,
tensorizer: ScriptTensorizer,
normalizer: VectorNormalizer,
):
super().__init__(model, output_layer, tensorizer)
self.normalizer = normalizer
@torch.jit.script_me... | BatchInput(
texts=resolve_texts(texts, multi_texts),
tokens=squeeze_2d(tokens),
languages=squeeze_1d(languages),
)
input_tensors = self.tensorizer(inputs)
logits = self.model(input_tensors)
return self.output_layer(logits)
class ScriptPyTextModuleWithD... | 77 | 77 | 257 | 13 | 64 | cakkaya/pytext | pytext/torchscript/module.py | Python | ScriptPyTextModuleWithDense | ScriptPyTextModuleWithDense | 57 | 86 | 57 | 57 | ce04bd7e8703a18880bffa0455da8e2e7deab689 | bigcode/the-stack | train |
111470305765f378beec243d | train | class | class ScriptPyTextEmbeddingModuleWithDenseIndex(ScriptPyTextEmbeddingModuleWithDense):
def __init__(
self,
model: torch.jit.ScriptModule,
tensorizer: ScriptTensorizer,
normalizer: VectorNormalizer,
index: int = 0,
concat_dense: bool = True,
):
super().__in... | class ScriptPyTextEmbeddingModuleWithDenseIndex(ScriptPyTextEmbeddingModuleWithDense):
| def __init__(
self,
model: torch.jit.ScriptModule,
tensorizer: ScriptTensorizer,
normalizer: VectorNormalizer,
index: int = 0,
concat_dense: bool = True,
):
super().__init__(model, tensorizer, normalizer, concat_dense)
self.index = torch.jit.Attrib... | _feat, dtype=torch.float)
sentence_embedding = self._forward(inputs, dense_tensor)
if self.concat_dense:
return torch.cat([sentence_embedding, dense_tensor], 1)
else:
return sentence_embedding
class ScriptPyTextEmbeddingModuleWithDenseIndex(ScriptPyTextEmbeddingModuleWit... | 64 | 64 | 148 | 18 | 45 | cakkaya/pytext | pytext/torchscript/module.py | Python | ScriptPyTextEmbeddingModuleWithDenseIndex | ScriptPyTextEmbeddingModuleWithDenseIndex | 180 | 195 | 180 | 180 | 5f3021c7b5634cfb9b98f5d7ed254a82adb600ef | bigcode/the-stack | train |
d176c141dfe2a5887a623ab3 | train | class | class ScriptModule(torch.jit.ScriptModule):
@torch.jit.script_method
def set_device(self, device: str):
self.tensorizer.set_device(device)
| class ScriptModule(torch.jit.ScriptModule):
@torch.jit.script_method
| def set_device(self, device: str):
self.tensorizer.set_device(device)
| [str]] = None, multi_texts: Optional[List[List[str]]] = None
) -> Optional[List[List[str]]]:
if texts is not None:
return squeeze_1d(texts)
return multi_texts
class ScriptModule(torch.jit.ScriptModule):
@torch.jit.script_method
| 64 | 64 | 35 | 17 | 46 | cakkaya/pytext | pytext/torchscript/module.py | Python | ScriptModule | ScriptModule | 20 | 23 | 20 | 21 | 9830c58e26249c6d424bc2e2c2ec3b6308fb4e21 | bigcode/the-stack | train |
fdbc53834f8ba7dcd49abbe8 | train | class | class ScriptPyTextEmbeddingModuleWithDense(ScriptPyTextEmbeddingModule):
def __init__(
self,
model: torch.jit.ScriptModule,
tensorizer: ScriptTensorizer,
normalizer: VectorNormalizer,
concat_dense: bool = False,
):
super().__init__(model, tensorizer)
self.... | class ScriptPyTextEmbeddingModuleWithDense(ScriptPyTextEmbeddingModule):
| def __init__(
self,
model: torch.jit.ScriptModule,
tensorizer: ScriptTensorizer,
normalizer: VectorNormalizer,
concat_dense: bool = False,
):
super().__init__(model, tensorizer)
self.normalizer = normalizer
self.concat_dense = torch.jit.Attribute(c... | self,
model: torch.jit.ScriptModule,
tensorizer: ScriptTensorizer,
index: int = 0,
):
super().__init__(model, tensorizer)
self.index = torch.jit.Attribute(index, int)
@torch.jit.script_method
def _forward(self, inputs: ScriptBatchInput):
input_tensors = self... | 109 | 109 | 364 | 15 | 94 | cakkaya/pytext | pytext/torchscript/module.py | Python | ScriptPyTextEmbeddingModuleWithDense | ScriptPyTextEmbeddingModuleWithDense | 134 | 177 | 134 | 134 | fe1ed8223752e0b44b516f7841cae701fa7b601e | bigcode/the-stack | train |
1719312c58e94217ba257bef | train | class | class WRCEmbedding(gluon.HybridBlock):
def __init__(self, word_embedding_size, word_radical_embedding_size,
char_embedding_size,
embedding_dim, dropout=0.5, prefix=None,
params=None):
super(WRCEmbedding, self).__init__(prefix, params)
with self.name... | class WRCEmbedding(gluon.HybridBlock):
| def __init__(self, word_embedding_size, word_radical_embedding_size,
char_embedding_size,
embedding_dim, dropout=0.5, prefix=None,
params=None):
super(WRCEmbedding, self).__init__(prefix, params)
with self.name_scope():
self.word_embeddi... | self.dropout(attention)
# attention = self.dropout(
# F.Activation(self.nn(attention), act_type='softrelu')
# )
# fc_in = self.layers_attention(attention)
fc_in = attention
return self.fc(fc_in)
def set_network_unroll(self, word_length, character_length):
... | 96 | 96 | 321 | 10 | 85 | bigdata-ustc/CangJie | CangJie/CTC/RFAG/Module/sym/net/WRCLSTM.py | Python | WRCEmbedding | WRCEmbedding | 154 | 191 | 154 | 154 | dbbec5841f732101cb4916756eab461137a023b0 | bigcode/the-stack | train |
ac4193a30e30f175492f24cb | train | class | class WRCLSTM(gluon.HybridBlock):
def __init__(self,
net_type,
class_num, embedding_dim,
lstm_hidden=None, embedding_size=None,
embed_dropout=0.5, fc_dropout=0.5,
**kwargs):
r"""Our method: 包含词和字,以及字、词部首的网络模型"""
sup... | class WRCLSTM(gluon.HybridBlock):
| def __init__(self,
net_type,
class_num, embedding_dim,
lstm_hidden=None, embedding_size=None,
embed_dropout=0.5, fc_dropout=0.5,
**kwargs):
r"""Our method: 包含词和字,以及字、词部首的网络模型"""
super(WRCLSTM, self).__init__(**kwarg... | # coding: utf-8
# 2019/12/28 @ tongshiwei
from longling.ML.MxnetHelper.gallery.layer.attention import \
DotProductAttentionCell
import mxnet as mx
from mxnet import gluon
class WRCLSTM(gluon.HybridBlock):
| 64 | 256 | 1,265 | 10 | 53 | bigdata-ustc/CangJie | CangJie/CTC/RFAG/Module/sym/net/WRCLSTM.py | Python | WRCLSTM | WRCLSTM | 9 | 151 | 9 | 9 | e2c8f8c286e5476dc538827cc2dc82e7bf44c324 | bigcode/the-stack | train |
3c33dd01d4f562a73ae32640 | train | class | class Carousel(Widget):
"""Represents the Carousel widget.
https://getbootstrap.com/docs/4.1/components/carousel/
"""
ROOT = ParametrizedLocator("{@locator}")
SLIDE_CONTROL = "./a[@data-slide={}]"
INDICATOR = "./ol/li[@data-slide-to={}]"
CAPTION = ".//div[contains(@class, 'active')]/div[co... | class Carousel(Widget):
| """Represents the Carousel widget.
https://getbootstrap.com/docs/4.1/components/carousel/
"""
ROOT = ParametrizedLocator("{@locator}")
SLIDE_CONTROL = "./a[@data-slide={}]"
INDICATOR = "./ol/li[@data-slide-to={}]"
CAPTION = ".//div[contains(@class, 'active')]/div[contains(@class, 'carousel... | from wait_for import wait_for
from widgetastic.utils import ParametrizedLocator
from widgetastic.xpath import quote
from widgetastic.widget import do_not_read_this_widget, Widget
class Carousel(Widget):
| 42 | 118 | 394 | 5 | 36 | mfalesni/widgetastic.bootstrap | src/widgetastic_bootstrap/carousel.py | Python | Carousel | Carousel | 7 | 56 | 7 | 7 | 51b5f47876f4db402715a71d853ffd7e60a3aaaf | bigcode/the-stack | train |
8d6fa0bb4d4c6c11f437f821 | train | class | class naive_bayes:
def __init__(self, feature, label):
self.feature = feature.transpose()
self.label = label.transpose().flatten(1)
self.positive = np.count_nonzero(self.label == 1) * 1.0
self.negative = np.count_nonzero(self.label == -1) * 1.0
def train(self):
positive_... | class naive_bayes:
| def __init__(self, feature, label):
self.feature = feature.transpose()
self.label = label.transpose().flatten(1)
self.positive = np.count_nonzero(self.label == 1) * 1.0
self.negative = np.count_nonzero(self.label == -1) * 1.0
def train(self):
positive_dict = {}
n... | """
@ jetou
@ cart decision_tree
@ date 2017 10 31
"""
import numpy as np
class naive_bayes:
| 34 | 81 | 272 | 5 | 28 | haohonglin/DeepLearning-1 | books/李航-统计学习/machine_learning_algorithm-master/naive_bayes/naive_bayes.py | Python | naive_bayes | naive_bayes | 10 | 41 | 10 | 10 | d7b790c1c401a3804393aa05967c29db50ece80c | bigcode/the-stack | train |
dc99d17b59eb68bdb8ddc8b1 | train | class | class LoginView(DjangoLoginView):
def render_to_response(self, context, **response_kwargs):
if not User.objects.filter(id=1).exists():
return HttpResponseRedirect(reverse_lazy("register"))
return super(LoginView, self).render_to_response(context, **response_kwargs)
| class LoginView(DjangoLoginView):
| def render_to_response(self, context, **response_kwargs):
if not User.objects.filter(id=1).exists():
return HttpResponseRedirect(reverse_lazy("register"))
return super(LoginView, self).render_to_response(context, **response_kwargs)
| user = form.save()
user = authenticate(request=self.request, username=user.username, password=form.cleaned_data['password1'])
if user and user.is_active:
login(request=self.request, user=user)
return super(RegisterSuperUserView, self).form_valid(form)
class LoginView(DjangoLoginView... | 64 | 64 | 60 | 8 | 56 | StevenKangWei/words | words/viewer/views/account.py | Python | LoginView | LoginView | 25 | 30 | 25 | 26 | 29bd53dc577a74884bb655a18a6a7bfd0fbd6f68 | bigcode/the-stack | train |
01237e6b7234d107c12524e5 | train | class | class RegisterSuperUserView(FormView):
template_name = "registration/register.html"
form_class = forms.RegisterSuperUserForm
success_url = reverse_lazy("index")
def form_valid(self, form):
user = form.save()
user = authenticate(request=self.request, username=user.username, password=for... | class RegisterSuperUserView(FormView):
| template_name = "registration/register.html"
form_class = forms.RegisterSuperUserForm
success_url = reverse_lazy("index")
def form_valid(self, form):
user = form.save()
user = authenticate(request=self.request, username=user.username, password=form.cleaned_data['password1'])
if ... | reverse_lazy
from django.views.generic.edit import FormView
from django.contrib.auth import authenticate, login
from django.contrib.auth.views import LoginView as DjangoLoginView
from django.contrib.auth.models import User
from django.http.response import HttpResponseRedirect
from viewer import forms
class RegisterSu... | 64 | 64 | 101 | 8 | 55 | StevenKangWei/words | words/viewer/views/account.py | Python | RegisterSuperUserView | RegisterSuperUserView | 11 | 22 | 11 | 12 | e9558b703cfb993146ea4d11799490b9313ff190 | bigcode/the-stack | train |
0aa88165cd3f9000b5480778 | train | class | @COMPONENTS.register_module()
class ModifiedVGG(nn.Module):
"""A modified VGG discriminator with input size 128 x 128.
It is used to train SRGAN and ESRGAN.
Args:
in_channels (int): Channel number of inputs. Default: 3.
mid_channels (int): Channel number of base intermediate features.
... | @COMPONENTS.register_module()
class ModifiedVGG(nn.Module):
| """A modified VGG discriminator with input size 128 x 128.
It is used to train SRGAN and ESRGAN.
Args:
in_channels (int): Channel number of inputs. Default: 3.
mid_channels (int): Channel number of base intermediate features.
Default: 64.
"""
def __init__(self, in_chan... | import torch.nn as nn
from mmcv.runner import load_checkpoint
from mmedit.models.registry import COMPONENTS
from mmedit.utils import get_root_logger
@COMPONENTS.register_module()
class ModifiedVGG(nn.Module):
| 48 | 256 | 1,232 | 14 | 33 | Yshuo-Li/mmediting-test | mmedit/models/components/discriminators/modified_vgg.py | Python | ModifiedVGG | ModifiedVGG | 8 | 117 | 8 | 9 | cb497df8f60e0ba47d54524d0e85f642d6cb1dd5 | bigcode/the-stack | train |
c8c10b93b253cbb1d94b9ea7 | train | class | class FigureCanvasWxAgg(FigureCanvasAgg, FigureCanvasWx):
"""
The FigureCanvas contains the figure and does event handling.
In the wxPython backend, it is derived from wxPanel, and (usually)
lives inside a frame instantiated by a FigureManagerWx. The parent
window probably implements a wxSizer to c... | class FigureCanvasWxAgg(FigureCanvasAgg, FigureCanvasWx):
| """
The FigureCanvas contains the figure and does event handling.
In the wxPython backend, it is derived from wxPanel, and (usually)
lives inside a frame instantiated by a FigureManagerWx. The parent
window probably implements a wxSizer to control the displayed
control size - but we give a hint... | DEBUG_MSG, NavigationToolbar2Wx, error_msg_wx, \
draw_if_interactive, show, Toolbar, backend_version
import wx
class FigureFrameWxAgg(FigureFrameWx):
def get_canvas(self, fig):
return FigureCanvasWxAgg(self, -1, fig)
def _get_toolbar(self, statbar):
if matplotlib.rcParams['toolbar']=='cla... | 148 | 148 | 496 | 14 | 133 | stefanv/matplotlib | lib/matplotlib/backends/backend_wxagg.py | Python | FigureCanvasWxAgg | FigureCanvasWxAgg | 43 | 106 | 43 | 43 | b623c39af84ddc783dcda336ea95e1aa56178521 | bigcode/the-stack | train |
1ece0cff3d96f2e83194dd2d | train | function | def _convert_agg_to_wx_bitmap(agg, bbox):
"""
Convert the region of the agg buffer bounded by bbox to a wx.Bitmap. If
bbox is None, the entire buffer is converted.
Note: agg must be a backend_agg.RendererAgg instance.
"""
if bbox is None:
# agg => rgba buffer -> bitmap
return w... | def _convert_agg_to_wx_bitmap(agg, bbox):
| """
Convert the region of the agg buffer bounded by bbox to a wx.Bitmap. If
bbox is None, the entire buffer is converted.
Note: agg must be a backend_agg.RendererAgg instance.
"""
if bbox is None:
# agg => rgba buffer -> bitmap
return wx.BitmapFromBufferRGBA(int(agg.width), int... | image.SetData(agg.tostring_rgb())
return image
else:
# agg => rgba buffer -> bitmap => clipped bitmap => image
return wx.ImageFromBitmap(_WX28_clipped_agg_as_bitmap(agg, bbox))
def _convert_agg_to_wx_bitmap(agg, bbox):
| 64 | 64 | 137 | 14 | 50 | stefanv/matplotlib | lib/matplotlib/backends/backend_wxagg.py | Python | _convert_agg_to_wx_bitmap | _convert_agg_to_wx_bitmap | 153 | 166 | 153 | 153 | 30e0ff965ccd8a0a079c98106e58e22fca8cebd7 | bigcode/the-stack | train |
6be86207ecb0f4059ed7f40b | train | function | def _WX28_clipped_agg_as_bitmap(agg, bbox):
"""
Convert the region of a the agg buffer bounded by bbox to a wx.Bitmap.
Note: agg must be a backend_agg.RendererAgg instance.
"""
l, b, width, height = bbox.bounds
r = l + width
t = b + height
srcBmp = wx.BitmapFromBufferRGBA(int(agg.width... | def _WX28_clipped_agg_as_bitmap(agg, bbox):
| """
Convert the region of a the agg buffer bounded by bbox to a wx.Bitmap.
Note: agg must be a backend_agg.RendererAgg instance.
"""
l, b, width, height = bbox.bounds
r = l + width
t = b + height
srcBmp = wx.BitmapFromBufferRGBA(int(agg.width), int(agg.height),
agg.buffer_rgba(... | RGBA(int(agg.width), int(agg.height),
agg.buffer_rgba(0, 0))
else:
# agg => rgba buffer -> bitmap => clipped bitmap
return _WX28_clipped_agg_as_bitmap(agg, bbox)
def _WX28_clipped_agg_as_bitmap(agg, bbox):
| 68 | 68 | 229 | 15 | 53 | stefanv/matplotlib | lib/matplotlib/backends/backend_wxagg.py | Python | _WX28_clipped_agg_as_bitmap | _WX28_clipped_agg_as_bitmap | 169 | 197 | 169 | 169 | 1d58279babf7bd5210fbe347956f34eee06f278f | bigcode/the-stack | train |
82295cf729664c66620a284d | train | class | class NavigationToolbar2WxAgg(NavigationToolbar2Wx):
def get_canvas(self, frame, fig):
return FigureCanvasWxAgg(frame, -1, fig)
| class NavigationToolbar2WxAgg(NavigationToolbar2Wx):
| def get_canvas(self, frame, fig):
return FigureCanvasWxAgg(frame, -1, fig)
| )
# Restore the current view; this is needed because the
# artist contains methods rely on particular attributes
# of the rendered figure for determining things like
# bounding boxes.
if self._isDrawn:
self.draw()
class NavigationToolbar2WxAgg(NavigationToolbar2Wx):
| 64 | 64 | 35 | 12 | 52 | stefanv/matplotlib | lib/matplotlib/backends/backend_wxagg.py | Python | NavigationToolbar2WxAgg | NavigationToolbar2WxAgg | 108 | 110 | 108 | 108 | 681df15cffd4b2695c45c91c853d237e690d5517 | bigcode/the-stack | train |
e7735baef1a68503fff4dc19 | train | class | class FigureFrameWxAgg(FigureFrameWx):
def get_canvas(self, fig):
return FigureCanvasWxAgg(self, -1, fig)
def _get_toolbar(self, statbar):
if matplotlib.rcParams['toolbar']=='classic':
toolbar = NavigationToolbarWx(self.canvas, True)
elif matplotlib.rcParams['toolbar']=='too... | class FigureFrameWxAgg(FigureFrameWx):
| def get_canvas(self, fig):
return FigureCanvasWxAgg(self, -1, fig)
def _get_toolbar(self, statbar):
if matplotlib.rcParams['toolbar']=='classic':
toolbar = NavigationToolbarWx(self.canvas, True)
elif matplotlib.rcParams['toolbar']=='toolbar2':
toolbar = Navigatio... | 8')
from backend_wx import FigureManager, FigureManagerWx, FigureCanvasWx, \
FigureFrameWx, DEBUG_MSG, NavigationToolbar2Wx, error_msg_wx, \
draw_if_interactive, show, Toolbar, backend_version
import wx
class FigureFrameWxAgg(FigureFrameWx):
| 64 | 64 | 104 | 10 | 53 | stefanv/matplotlib | lib/matplotlib/backends/backend_wxagg.py | Python | FigureFrameWxAgg | FigureFrameWxAgg | 29 | 41 | 29 | 29 | 75ee48354d9f151705fa7d42b1b92648c3e0da65 | bigcode/the-stack | train |
448b34d1751f465d052baeee | train | function | def _convert_agg_to_wx_image(agg, bbox):
"""
Convert the region of the agg buffer bounded by bbox to a wx.Image. If
bbox is None, the entire buffer is converted.
Note: agg must be a backend_agg.RendererAgg instance.
"""
if bbox is None:
# agg => rgb -> image
image = wx.EmptyIma... | def _convert_agg_to_wx_image(agg, bbox):
| """
Convert the region of the agg buffer bounded by bbox to a wx.Image. If
bbox is None, the entire buffer is converted.
Note: agg must be a backend_agg.RendererAgg instance.
"""
if bbox is None:
# agg => rgb -> image
image = wx.EmptyImage(int(agg.width), int(agg.height))
... | , fig)
figmgr = frame.get_figure_manager()
if matplotlib.is_interactive():
figmgr.frame.Show()
return figmgr
#
# agg/wxPython image conversion functions (wxPython >= 2.8)
#
def _convert_agg_to_wx_image(agg, bbox):
| 64 | 64 | 144 | 14 | 50 | stefanv/matplotlib | lib/matplotlib/backends/backend_wxagg.py | Python | _convert_agg_to_wx_image | _convert_agg_to_wx_image | 136 | 150 | 136 | 136 | 45f606dd52af3edff881f35723a78ec778ad34bd | bigcode/the-stack | train |
c628d6c0bd19a4db6ab9cf0f | train | function | def new_figure_manager(num, *args, **kwargs):
"""
Create a new figure manager instance
"""
# in order to expose the Figure constructor to the pylab
# interface we need to create the figure here
DEBUG_MSG("new_figure_manager()", 3, None)
backend_wx._create_wx_app()
FigureClass = kwargs.p... | def new_figure_manager(num, *args, **kwargs):
| """
Create a new figure manager instance
"""
# in order to expose the Figure constructor to the pylab
# interface we need to create the figure here
DEBUG_MSG("new_figure_manager()", 3, None)
backend_wx._create_wx_app()
FigureClass = kwargs.pop('FigureClass', Figure)
fig = FigureClas... | # bounding boxes.
if self._isDrawn:
self.draw()
class NavigationToolbar2WxAgg(NavigationToolbar2Wx):
def get_canvas(self, frame, fig):
return FigureCanvasWxAgg(frame, -1, fig)
def new_figure_manager(num, *args, **kwargs):
| 64 | 64 | 136 | 13 | 51 | stefanv/matplotlib | lib/matplotlib/backends/backend_wxagg.py | Python | new_figure_manager | new_figure_manager | 113 | 128 | 113 | 113 | c496815604e306af8fdb3283dfcf5e63abcf0e84 | bigcode/the-stack | train |
016c9a1f84c7fb3c1913e653 | train | function | def predict(url):
X = preprocess(url)
interpreter.set_tensor(input_index, X)
interpreter.invoke()
preds = interpreter.get_tensor(output_index)
actual_pred = preds[0].tolist()
return actual_pred
| def predict(url):
| X = preprocess(url)
interpreter.set_tensor(input_index, X)
interpreter.invoke()
preds = interpreter.get_tensor(output_index)
actual_pred = preds[0].tolist()
return actual_pred
| return img
def preprocess(url):
download = download_image(url)
img = prepare_image(download, (150, 150))
x = np.array(img, dtype='float32')
x = x/ 255
X = np.array([x])
return X
def predict(url):
| 64 | 64 | 47 | 4 | 59 | ziritrion/ml-zoomcamp | 09_serverless/lambda_function.py | Python | predict | predict | 40 | 48 | 40 | 40 | 9f595d65ec8adad26c7c9577f511234443beb81d | bigcode/the-stack | train |
18dcb4b5e0a08868b7359e0c | train | function | def download_image(url):
with request.urlopen(url) as resp:
buffer = resp.read()
stream = BytesIO(buffer)
img = Image.open(stream)
return img
| def download_image(url):
| with request.urlopen(url) as resp:
buffer = resp.read()
stream = BytesIO(buffer)
img = Image.open(stream)
return img
| cats-dogs-v2.tflite
interpreter = tflite.Interpreter(model_path='cats-dogs-v2.tflite')
interpreter.allocate_tensors()
input_index = interpreter.get_input_details()[0]['index']
output_index = interpreter.get_output_details()[0]['index']
def download_image(url):
| 64 | 64 | 38 | 5 | 59 | ziritrion/ml-zoomcamp | 09_serverless/lambda_function.py | Python | download_image | download_image | 19 | 24 | 19 | 19 | d4dc7c0e1c23439f05d221d2310264f199349707 | bigcode/the-stack | train |
d3cb996abc9857d1758983c1 | train | function | def lambda_handler(event, context):
url = event['url']
result = predict(url)
return result | def lambda_handler(event, context):
| url = event['url']
result = predict(url)
return result | = np.array([x])
return X
def predict(url):
X = preprocess(url)
interpreter.set_tensor(input_index, X)
interpreter.invoke()
preds = interpreter.get_tensor(output_index)
actual_pred = preds[0].tolist()
return actual_pred
def lambda_handler(event, context):
| 64 | 64 | 23 | 7 | 56 | ziritrion/ml-zoomcamp | 09_serverless/lambda_function.py | Python | lambda_handler | lambda_handler | 50 | 53 | 50 | 50 | 3347d2debac5db9003c2f064005af41bb8f1931d | bigcode/the-stack | train |
9e50a9971a0f4aedc01fd02b | train | function | def preprocess(url):
download = download_image(url)
img = prepare_image(download, (150, 150))
x = np.array(img, dtype='float32')
x = x/ 255
X = np.array([x])
return X
| def preprocess(url):
| download = download_image(url)
img = prepare_image(download, (150, 150))
x = np.array(img, dtype='float32')
x = x/ 255
X = np.array([x])
return X
| ()
stream = BytesIO(buffer)
img = Image.open(stream)
return img
def prepare_image(img, target_size):
if img.mode != 'RGB':
img = img.convert('RGB')
img = img.resize(target_size, Image.NEAREST)
return img
def preprocess(url):
| 64 | 64 | 56 | 4 | 59 | ziritrion/ml-zoomcamp | 09_serverless/lambda_function.py | Python | preprocess | preprocess | 32 | 38 | 32 | 32 | fc48329db8c8c3bb8cb3c5a32917f8faeea886d4 | bigcode/the-stack | train |
1ff3a65f724a10470aba7b75 | train | function | def prepare_image(img, target_size):
if img.mode != 'RGB':
img = img.convert('RGB')
img = img.resize(target_size, Image.NEAREST)
return img
| def prepare_image(img, target_size):
| if img.mode != 'RGB':
img = img.convert('RGB')
img = img.resize(target_size, Image.NEAREST)
return img
| _details()[0]['index']
output_index = interpreter.get_output_details()[0]['index']
def download_image(url):
with request.urlopen(url) as resp:
buffer = resp.read()
stream = BytesIO(buffer)
img = Image.open(stream)
return img
def prepare_image(img, target_size):
| 64 | 64 | 41 | 8 | 55 | ziritrion/ml-zoomcamp | 09_serverless/lambda_function.py | Python | prepare_image | prepare_image | 26 | 30 | 26 | 26 | a9252d14400c7e7aef9bf8d44b246eec07ee54c9 | bigcode/the-stack | train |
ed43fa3ed8cb9ff6793c9085 | train | class | @pytest.mark.skipif(sys.platform == 'win32', reason="Skip test on Windows")
class TestCopyTree:
"""Tests for ``filesystem.copy_tree``"""
def test_existing_dir(self, stage):
"""Test copying to an existing directory."""
with fs.working_dir(str(stage)):
fs.copy_tree('source', 'dest')
... | @pytest.mark.skipif(sys.platform == 'win32', reason="Skip test on Windows")
class TestCopyTree:
| """Tests for ``filesystem.copy_tree``"""
def test_existing_dir(self, stage):
"""Test copying to an existing directory."""
with fs.working_dir(str(stage)):
fs.copy_tree('source', 'dest')
assert os.path.exists('dest/a/b/2')
def test_non_existing_dir(self, stage):
... | check_added_exe_permissions('source/a/b/2', 'dest/2')
check_added_exe_permissions('source/a/b/3', 'dest/3')
def test_non_existing_src(self, stage):
"""Test using a non-existing source."""
with fs.working_dir(str(stage)):
with pytest.raises(IOError, match='No suc... | 194 | 194 | 649 | 23 | 171 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | TestCopyTree | TestCopyTree | 152 | 232 | 152 | 153 | 27d2e9715b806919dbc7b1aa9fa1fcfd16a1db3c | bigcode/the-stack | train |
88ef9715d072ae5721f984f3 | train | class | @pytest.mark.skipif(sys.platform == 'win32', reason="Skip test on Windows")
class TestInstallTree:
"""Tests for ``filesystem.install_tree``"""
def test_existing_dir(self, stage):
"""Test installing to an existing directory."""
with fs.working_dir(str(stage)):
fs.install_tree('sourc... | @pytest.mark.skipif(sys.platform == 'win32', reason="Skip test on Windows")
class TestInstallTree:
| """Tests for ``filesystem.install_tree``"""
def test_existing_dir(self, stage):
"""Test installing to an existing directory."""
with fs.working_dir(str(stage)):
fs.install_tree('source', 'dest')
assert os.path.exists('dest/a/b/2')
check_added_exe_permission... | fs.copy_tree('source/g/*', 'dest')
assert os.path.exists('dest/i/8')
assert os.path.exists('dest/i/9')
assert os.path.exists('dest/j/10')
def test_non_existing_src(self, stage):
"""Test using a non-existing source."""
with fs.working_dir(str(stage)):
... | 184 | 184 | 616 | 23 | 161 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | TestInstallTree | TestInstallTree | 235 | 306 | 235 | 236 | 301141df94ef8b8a89bc38f00747502d1675d8b0 | bigcode/the-stack | train |
3f06069c1ebb812e78a190d2 | train | function | def test_move_transaction_rollback(tmpdir):
fake_library = tmpdir.mkdir('lib').join('libfoo.so')
fake_library.write('Just some fake content.')
h = fs.hash_directory(str(tmpdir))
try:
with fs.replace_directory_transaction(str(tmpdir.join('lib'))):
assert h != fs.hash_directory(str(... | def test_move_transaction_rollback(tmpdir):
| fake_library = tmpdir.mkdir('lib').join('libfoo.so')
fake_library.write('Just some fake content.')
h = fs.hash_directory(str(tmpdir))
try:
with fs.replace_directory_transaction(str(tmpdir.join('lib'))):
assert h != fs.hash_directory(str(tmpdir))
fake_library = tmpdir.mk... | ('lib').join('libfoo.so')
fake_library.write('Other content.')
new_md5 = fs.hash_directory(str(tmpdir))
assert old_md5 != fs.hash_directory(str(tmpdir))
assert new_md5 == fs.hash_directory(str(tmpdir))
def test_move_transaction_rollback(tmpdir):
| 64 | 64 | 121 | 9 | 55 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_move_transaction_rollback | test_move_transaction_rollback | 335 | 351 | 335 | 336 | 804e29793b48496466deeb3a197432cf4f3d147f | bigcode/the-stack | train |
c0fbc96c5bd1c74cb79067ce | train | function | def test_lexists_islink_isdir(tmpdir):
root = str(tmpdir)
# Create a directory and a file, an a bunch of symlinks.
dir = os.path.join(root, "dir")
file = os.path.join(root, "file")
nonexistent = os.path.join(root, "does_not_exist")
symlink_to_dir = os.path.join(root, "symlink_to_dir")
symli... | def test_lexists_islink_isdir(tmpdir):
| root = str(tmpdir)
# Create a directory and a file, an a bunch of symlinks.
dir = os.path.join(root, "dir")
file = os.path.join(root, "file")
nonexistent = os.path.join(root, "does_not_exist")
symlink_to_dir = os.path.join(root, "symlink_to_dir")
symlink_to_file = os.path.join(root, "symlin... | :
f.write(b'#!/interpreter')
os.chmod('not_executable_with_shebang', 0o100664)
os.symlink('executable_script', 'symlink_to_executable_script')
assert fs.is_nonsymlink_exe_with_shebang('executable_script')
assert not fs.is_nonsymlink_exe_with_shebang('executable_but_not_scri... | 147 | 147 | 490 | 12 | 135 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_lexists_islink_isdir | test_lexists_islink_isdir | 703 | 735 | 703 | 703 | 38dd26aad64b4605036964722a2136896c5e35c5 | bigcode/the-stack | train |
6b455e7a928c98d94812fa98 | train | class | class RegisterVisitor(object):
"""A directory visitor that keeps track of all visited paths"""
def __init__(self, root, follow_dirs=True, follow_symlink_dirs=True):
self.files = []
self.dirs_before = []
self.symlinked_dirs_before = []
self.dirs_after = []
self.symlinked_d... | class RegisterVisitor(object):
| """A directory visitor that keeps track of all visited paths"""
def __init__(self, root, follow_dirs=True, follow_symlink_dirs=True):
self.files = []
self.dirs_before = []
self.symlinked_dirs_before = []
self.dirs_after = []
self.symlinked_dirs_after = []
self.ro... | dir(symlink_to_file) == (True, True, False)
assert fs.lexists_islink_isdir(symlink_to_dangling_symlink) == (True, True, False)
assert fs.lexists_islink_isdir(symlink_to_symlink_to_dir) == (True, True, True)
assert fs.lexists_islink_isdir(symlink_to_symlink_to_file) == (True, True, False)
class RegisterVisit... | 99 | 99 | 332 | 5 | 94 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | RegisterVisitor | RegisterVisitor | 738 | 775 | 738 | 738 | e86b991bbdca35e61ca07aac20a14f5be717938d | bigcode/the-stack | train |
f69e5042f4d81decc0ad5115 | train | function | def test_keep_modification_time(tmpdir):
file1 = tmpdir.ensure('file1')
file2 = tmpdir.ensure('file2')
# Shift the modification time of the file 10 seconds back:
mtime1 = file1.mtime() - 10
file1.setmtime(mtime1)
with fs.keep_modification_time(file1.strpath,
... | def test_keep_modification_time(tmpdir):
| file1 = tmpdir.ensure('file1')
file2 = tmpdir.ensure('file2')
# Shift the modification time of the file 10 seconds back:
mtime1 = file1.mtime() - 10
file1.setmtime(mtime1)
with fs.keep_modification_time(file1.strpath,
file2.strpath,
... | 2)):
raise RuntimeError('Mock a failure')
# Check both files have been restored correctly
# and have not been mixed
assert file1.read().strip() == 'file1'
assert file2.read().strip() == 'file2'
def test_keep_modification_time(tmpdir):
| 64 | 64 | 157 | 9 | 55 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_keep_modification_time | test_keep_modification_time | 651 | 669 | 651 | 651 | 0af40f968ee1ec12bda72d6ae5e32ab9091ecac5 | bigcode/the-stack | train |
60a8b1a2be6f6ffbb948510c | train | function | @pytest.mark.regression('10601')
@pytest.mark.regression('10603')
def test_recursive_search_of_headers_from_prefix(
installation_dir_with_headers
):
# Try to inspect recursively from <prefix> and ensure we don't get
# subdirectories of the '<prefix>/include' path
prefix = str(installation_dir_with_h... | @pytest.mark.regression('10601')
@pytest.mark.regression('10603')
def test_recursive_search_of_headers_from_prefix(
installation_dir_with_headers
):
# Try to inspect recursively from <prefix> and ensure we don't get
# subdirectories of the '<prefix>/include' path
| prefix = str(installation_dir_with_headers)
header_list = fs.find_all_headers(prefix)
include_dirs = header_list.directories
if sys.platform == "win32":
header_list = [header.replace("/", "\\") for header in header_list]
include_dirs = [dir.replace("/", "\\") for dir in include_dirs]
... | .so')
fake_library.write('Other content.')
raise RuntimeError('')
except RuntimeError:
pass
assert h == fs.hash_directory(str(tmpdir))
@pytest.mark.regression('10601')
@pytest.mark.regression('10603')
def test_recursive_search_of_headers_from_prefix(
installation_dir_wit... | 95 | 95 | 319 | 61 | 34 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_recursive_search_of_headers_from_prefix | test_recursive_search_of_headers_from_prefix | 354 | 380 | 354 | 360 | fc0a7fe4f1226fe07d71306e7a9c50b122290a0b | bigcode/the-stack | train |
0cd5dae7c3f31358d506e0a6 | train | function | @pytest.mark.regression('7358')
@pytest.mark.parametrize('regex,replacement,filename,keyword_args', [
(r"\<malloc\.h\>", "<stdlib.h>", 'x86_cpuid_info.c', {}),
(r"CDIR", "CURRENT_DIRECTORY", 'selfextract.bsx',
{'stop_at': '__ARCHIVE_BELOW__'})
])
def test_filter_files_with_different_encodings(
rege... | @pytest.mark.regression('7358')
@pytest.mark.parametrize('regex,replacement,filename,keyword_args', [
(r"\<malloc\.h\>", "<stdlib.h>", 'x86_cpuid_info.c', {}),
(r"CDIR", "CURRENT_DIRECTORY", 'selfextract.bsx',
{'stop_at': '__ARCHIVE_BELOW__'})
])
def test_filter_files_with_different_encodings(
rege... | original_file = os.path.join(
spack.paths.test_path, 'data', 'filter_file', filename
)
target_file = os.path.join(str(tmpdir), filename)
shutil.copy(original_file, target_file)
# This should not raise exceptions
fs.filter_file(regex, replacement, target_file, **keyword_args)
# Check ... | @pytest.mark.regression('7358')
@pytest.mark.parametrize('regex,replacement,filename,keyword_args', [
(r"\<malloc\.h\>", "<stdlib.h>", 'x86_cpuid_info.c', {}),
(r"CDIR", "CURRENT_DIRECTORY", 'selfextract.bsx',
{'stop_at': '__ARCHIVE_BELOW__'})
])
def test_filter_files_with_different_encodings(
rege... | 145 | 83 | 278 | 145 | 0 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_filter_files_with_different_encodings | test_filter_files_with_different_encodings | 495 | 520 | 495 | 506 | ae4b0f9c69f1af88a0639a688e24a7980cc20d66 | bigcode/the-stack | train |
e287181bd8504297b5a32059 | train | function | @pytest.mark.parametrize('files_or_dirs', [
# Remove a file over the two that are present
[{'subdirs': None,
'files': ['spack.lock', 'spack.yaml'],
'remove': ['spack.lock']}],
# Remove the entire directory where two files are stored
[{'subdirs': 'myenv',
'files': ['spack.lock', 'spack.... | @pytest.mark.parametrize('files_or_dirs', [
# Remove a file over the two that are present
[{'subdirs': None,
'files': ['spack.lock', 'spack.yaml'],
'remove': ['spack.lock']}],
# Remove the entire directory where two files are stored
[{'subdirs': 'myenv',
'files': ['spack.lock', 'spack.... | to_be_removed, to_be_checked = [], []
for entry in files_or_dirs:
# Create relative dir
subdirs = entry['subdirs']
dir = tmpdir if not subdirs else tmpdir.ensure(
*subdirs.split('/'), dir=True
)
# Create files in the directory
files = entry['files']
... | @pytest.mark.parametrize('files_or_dirs', [
# Remove a file over the two that are present
[{'subdirs': None,
'files': ['spack.lock', 'spack.yaml'],
'remove': ['spack.lock']}],
# Remove the entire directory where two files are stored
[{'subdirs': 'myenv',
'files': ['spack.lock', 'spack.... | 553 | 231 | 772 | 553 | 0 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_safe_remove | test_safe_remove | 551 | 629 | 551 | 599 | 1c7fbb7212c1be40ec8453bf5f1a7338bf430b20 | bigcode/the-stack | train |
e1e10b863012cb1e100a9353 | train | function | @pytest.mark.parametrize('path,expected', path_list)
def test_prefixes(path, expected):
assert fs.prefixes(path) == expected
| @pytest.mark.parametrize('path,expected', path_list)
def test_prefixes(path, expected):
| assert fs.prefixes(path) == expected
| ']),
('./some/sub/dir', ['./some', './some/sub', './some/sub/dir']),
('another/sub/dir', ['another', 'another/sub', 'another/sub/dir'])
]
@pytest.mark.parametrize('path,expected', path_list)
def test_prefixes(path, expected):
| 63 | 64 | 29 | 19 | 44 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_prefixes | test_prefixes | 490 | 492 | 490 | 491 | 4630a0dfb4e2dff23d8eb92e3b7687684e218e46 | bigcode/the-stack | train |
9bfc94adca58224d3b65003b | train | function | @pytest.mark.parametrize('list_of_headers,expected_directories', dir_list)
def test_computation_of_header_directories(
list_of_headers, expected_directories
):
hl = fs.HeaderList(list_of_headers)
assert hl.directories == expected_directories
| @pytest.mark.parametrize('list_of_headers,expected_directories', dir_list)
def test_computation_of_header_directories(
list_of_headers, expected_directories
):
| hl = fs.HeaderList(list_of_headers)
assert hl.directories == expected_directories
| fx/include/subdir/foo.h', '/pfx/subdir/foo.h'],
['/pfx/include', '/pfx/subdir'])
]
@pytest.mark.parametrize('list_of_headers,expected_directories', dir_list)
def test_computation_of_header_directories(
list_of_headers, expected_directories
):
| 63 | 64 | 54 | 34 | 29 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_computation_of_header_directories | test_computation_of_header_directories | 401 | 406 | 401 | 404 | 0847bdca937be0f7b1ee96ec6f3ce219d23195e2 | bigcode/the-stack | train |
8e56d00ae90fede1a7426dec | train | function | @pytest.mark.skipif(sys.platform == 'win32', reason="Requires symlinks")
def test_visit_directory_tree_follow_all(noncyclical_dir_structure):
root = str(noncyclical_dir_structure)
visitor = RegisterVisitor(root, follow_dirs=True, follow_symlink_dirs=True)
fs.visit_directory_tree(root, visitor)
j = os.pa... | @pytest.mark.skipif(sys.platform == 'win32', reason="Requires symlinks")
def test_visit_directory_tree_follow_all(noncyclical_dir_structure):
| root = str(noncyclical_dir_structure)
visitor = RegisterVisitor(root, follow_dirs=True, follow_symlink_dirs=True)
fs.visit_directory_tree(root, visitor)
j = os.path.join
assert visitor.files == [
j('a', 'file_1'),
j('a', 'to_c', 'dangling_link'),
j('a', 'to_c', 'file_2'),
... | _dirs
def after_visit_dir(self, root, rel_path, depth):
self.check(root, rel_path, depth)
self.dirs_after.append(rel_path)
def after_visit_symlinked_dir(self, root, rel_path, depth):
self.check(root, rel_path, depth)
self.symlinked_dirs_after.append(rel_path)
@pytest.mark.skipi... | 105 | 105 | 351 | 32 | 73 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_visit_directory_tree_follow_all | test_visit_directory_tree_follow_all | 778 | 818 | 778 | 779 | 330a21b6b7b18a14eae3d0ba4ca0ccecb4c50c7e | bigcode/the-stack | train |
7eabeb6dd786aa0b9e8d905f | train | function | @pytest.mark.parametrize('path,entry,expected', paths)
def test_partition_path(path, entry, expected):
assert fs.partition_path(path, entry) == expected
| @pytest.mark.parametrize('path,entry,expected', paths)
def test_partition_path(path, entry, expected):
| assert fs.partition_path(path, entry) == expected
| '', [])),
('relative/path', 'relative', ([], 'relative', ['relative/path'])),
('relative/path', 'path', (['relative'], 'relative/path', []))
]
@pytest.mark.parametrize('path,entry,expected', paths)
def test_partition_path(path, entry, expected):
| 63 | 64 | 34 | 22 | 41 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_partition_path | test_partition_path | 470 | 472 | 470 | 471 | 0dac4c73a352cb42fb95ef781624c210ff884d0d | bigcode/the-stack | train |
32560facf6dbd404ddd97faf | train | function | def test_move_transaction_commit(tmpdir):
fake_library = tmpdir.mkdir('lib').join('libfoo.so')
fake_library.write('Just some fake content.')
old_md5 = fs.hash_directory(str(tmpdir))
with fs.replace_directory_transaction(str(tmpdir.join('lib'))):
fake_library = tmpdir.mkdir('lib').join('libfoo... | def test_move_transaction_commit(tmpdir):
| fake_library = tmpdir.mkdir('lib').join('libfoo.so')
fake_library.write('Just some fake content.')
old_md5 = fs.hash_directory(str(tmpdir))
with fs.replace_directory_transaction(str(tmpdir.join('lib'))):
fake_library = tmpdir.mkdir('lib').join('libfoo.so')
fake_library.write('Other con... | (fs.paths_containing_libs(all_dirs, ['libgfortran'])) ==
set(lib_to_dirs['libgfortran']))
assert (set(fs.paths_containing_libs(all_dirs, ['libirc'])) ==
set(lib_to_dirs['libirc']))
def test_move_transaction_commit(tmpdir):
| 63 | 64 | 122 | 8 | 55 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_move_transaction_commit | test_move_transaction_commit | 319 | 332 | 319 | 320 | 1864ba849bfdd5b0f984152e7b9c6017ad1a2c78 | bigcode/the-stack | train |
0b62cff1a0a9d301096c047d | train | class | class TestInstall:
"""Tests for ``filesystem.install``"""
def test_file_dest(self, stage):
"""Test using a filename as the destination."""
with fs.working_dir(str(stage)):
fs.install('source/1', 'dest/1')
assert os.path.exists('dest/1')
check_added_exe_perm... | class TestInstall:
| """Tests for ``filesystem.install``"""
def test_file_dest(self, stage):
"""Test using a filename as the destination."""
with fs.working_dir(str(stage)):
fs.install('source/1', 'dest/1')
assert os.path.exists('dest/1')
check_added_exe_permissions('source/1',... | match = '.* matches multiple files but .* is not a directory'
with pytest.raises(ValueError, match=match):
fs.copy('source/a/*/*', 'dest/1')
def check_added_exe_permissions(src, dst):
src_mode = os.stat(src).st_mode
dst_mode = os.stat(dst).st_mode
for perm in [stat.S_IXUSR, st... | 113 | 113 | 377 | 4 | 108 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | TestInstall | TestInstall | 103 | 149 | 103 | 103 | 8a654a4f0b235cac2733489f828662c03d9e2895 | bigcode/the-stack | train |
444a95618a6aae50c4c8d407 | train | function | @pytest.mark.regression('18441')
def test_content_of_files_with_same_name(tmpdir):
# Create two subdirectories containing a file with the same name,
# differentiate the files by their content
file1 = tmpdir.ensure('myenv1/spack.lock')
file2 = tmpdir.ensure('myenv2/spack.lock')
file1.write('file1'), ... | @pytest.mark.regression('18441')
def test_content_of_files_with_same_name(tmpdir):
# Create two subdirectories containing a file with the same name,
# differentiate the files by their content
| file1 = tmpdir.ensure('myenv1/spack.lock')
file2 = tmpdir.ensure('myenv2/spack.lock')
file1.write('file1'), file2.write('file2')
# Use 'safe_remove' to remove the two files
with pytest.raises(RuntimeError):
with fs.safe_remove(str(file1), str(file2)):
raise RuntimeError('Mock a ... | # Assert that files are restored
for entry in to_be_checked:
assert os.path.exists(entry)
@pytest.mark.regression('18441')
def test_content_of_files_with_same_name(tmpdir):
# Create two subdirectories containing a file with the same name,
# differentiate the files by their content
| 64 | 64 | 173 | 42 | 22 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_content_of_files_with_same_name | test_content_of_files_with_same_name | 632 | 648 | 632 | 635 | 400bb8c3c0cfcb45176402d89470df7867e9e540 | bigcode/the-stack | train |
dd8bd68a78774f51301edbb4 | train | function | def test_filter_files_multiple(tmpdir):
# All files given as input to this test must satisfy the pre-requisite
# that the 'replacement' string is not present in the file initially and
# that there's at least one match for the regex
original_file = os.path.join(
spack.paths.test_path, 'data', 'fi... | def test_filter_files_multiple(tmpdir):
# All files given as input to this test must satisfy the pre-requisite
# that the 'replacement' string is not present in the file initially and
# that there's at least one match for the regex
| original_file = os.path.join(
spack.paths.test_path, 'data', 'filter_file', 'x86_cpuid_info.c'
)
target_file = os.path.join(str(tmpdir), 'x86_cpuid_info.c')
shutil.copy(original_file, target_file)
# This should not raise exceptions
fs.filter_file(r'\<malloc.h\>', '<unistd.h>', target_fil... | '}
with open(target_file, mode='r', **extra_kwargs) as f:
assert replacement in f.read()
def test_filter_files_multiple(tmpdir):
# All files given as input to this test must satisfy the pre-requisite
# that the 'replacement' string is not present in the file initially and
# that there's at leas... | 79 | 79 | 265 | 54 | 25 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_filter_files_multiple | test_filter_files_multiple | 523 | 544 | 523 | 526 | f8df7899a6be1cf063d2e9a1123c45a45b20dc80 | bigcode/the-stack | train |
f267e8834cf7e750655afb05 | train | function | @pytest.mark.skipif(sys.platform == 'win32', reason="No shebang on Windows")
def test_is_nonsymlink_exe_with_shebang(tmpdir):
with tmpdir.as_cwd():
# Create an executable with shebang.
with open('executable_script', 'wb') as f:
f.write(b'#!/interpreter')
os.chmod('executable_scri... | @pytest.mark.skipif(sys.platform == 'win32', reason="No shebang on Windows")
def test_is_nonsymlink_exe_with_shebang(tmpdir):
| with tmpdir.as_cwd():
# Create an executable with shebang.
with open('executable_script', 'wb') as f:
f.write(b'#!/interpreter')
os.chmod('executable_script', 0o100775)
with open('executable_but_not_script', 'wb') as f:
f.write(b'#/not-a-shebang')
os.... | previous_dir = os.path.realpath(os.getcwd())
with fs.temporary_dir() as tmp_dir:
assert previous_dir != os.path.realpath(os.getcwd())
assert os.path.realpath(str(tmp_dir)) == os.path.realpath(os.getcwd())
@pytest.mark.skipif(sys.platform == 'win32', reason="No shebang on Windows")
def test_is_nonsy... | 86 | 86 | 289 | 35 | 51 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_is_nonsymlink_exe_with_shebang | test_is_nonsymlink_exe_with_shebang | 679 | 700 | 679 | 680 | 0fe491da637924216419097acefdbdc0438b9d68 | bigcode/the-stack | train |
21c83598ef91545f6c68beec | train | function | def check_added_exe_permissions(src, dst):
src_mode = os.stat(src).st_mode
dst_mode = os.stat(dst).st_mode
for perm in [stat.S_IXUSR, stat.S_IXGRP, stat.S_IXOTH]:
if src_mode & perm:
assert dst_mode & perm
| def check_added_exe_permissions(src, dst):
| src_mode = os.stat(src).st_mode
dst_mode = os.stat(dst).st_mode
for perm in [stat.S_IXUSR, stat.S_IXGRP, stat.S_IXOTH]:
if src_mode & perm:
assert dst_mode & perm
| is not a directory."""
with fs.working_dir(str(stage)):
match = '.* matches multiple files but .* is not a directory'
with pytest.raises(ValueError, match=match):
fs.copy('source/a/*/*', 'dest/1')
def check_added_exe_permissions(src, dst):
| 64 | 64 | 70 | 10 | 54 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | check_added_exe_permissions | check_added_exe_permissions | 95 | 100 | 95 | 95 | 46b8df00ce145341cc3cbfb7612c4fe1a8390905 | bigcode/the-stack | train |
c9bd4b4ef8918ff9b9e044ed | train | function | @pytest.mark.regression('29687')
@pytest.mark.parametrize('initial_mode', [
stat.S_IRUSR | stat.S_IXUSR,
stat.S_IWGRP
])
@pytest.mark.skipif(sys.platform == 'win32', reason='Windows might change permissions')
def test_remove_linked_tree_doesnt_change_file_permission(tmpdir, initial_mode):
# Here we test tha... | @pytest.mark.regression('29687')
@pytest.mark.parametrize('initial_mode', [
stat.S_IRUSR | stat.S_IXUSR,
stat.S_IWGRP
])
@pytest.mark.skipif(sys.platform == 'win32', reason='Windows might change permissions')
def test_remove_linked_tree_doesnt_change_file_permission(tmpdir, initial_mode):
# Here we test tha... | file_instead_of_dir = tmpdir.ensure('foo')
file_instead_of_dir.chmod(initial_mode)
initial_stat = os.stat(str(file_instead_of_dir))
fs.remove_linked_tree(str(file_instead_of_dir))
final_stat = os.stat(str(file_instead_of_dir))
assert final_stat == initial_stat
| @pytest.mark.regression('29687')
@pytest.mark.parametrize('initial_mode', [
stat.S_IRUSR | stat.S_IXUSR,
stat.S_IWGRP
])
@pytest.mark.skipif(sys.platform == 'win32', reason='Windows might change permissions')
def test_remove_linked_tree_doesnt_change_file_permission(tmpdir, initial_mode):
# Here we test tha... | 125 | 64 | 196 | 125 | 0 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_remove_linked_tree_doesnt_change_file_permission | test_remove_linked_tree_doesnt_change_file_permission | 871 | 886 | 871 | 880 | 6c2bb352dfab7563bd6fd5ac5110715f9694c6c0 | bigcode/the-stack | train |
666f5e0911ddc73e38d6ae7f | train | function | @pytest.mark.skipif(sys.platform == 'win32', reason="Requires symlinks")
def test_visit_directory_tree_follow_dirs(noncyclical_dir_structure):
root = str(noncyclical_dir_structure)
visitor = RegisterVisitor(root, follow_dirs=True, follow_symlink_dirs=False)
fs.visit_directory_tree(root, visitor)
j = os.... | @pytest.mark.skipif(sys.platform == 'win32', reason="Requires symlinks")
def test_visit_directory_tree_follow_dirs(noncyclical_dir_structure):
| root = str(noncyclical_dir_structure)
visitor = RegisterVisitor(root, follow_dirs=True, follow_symlink_dirs=False)
fs.visit_directory_tree(root, visitor)
j = os.path.join
assert visitor.files == [
j('a', 'file_1'),
j('a', 'to_file_1'),
j('c', 'dangling_link'),
j('c', ... | assert visitor.symlinked_dirs_after == [
j('a', 'to_c'),
j('b', 'to_c'),
j('b'),
]
@pytest.mark.skipif(sys.platform == 'win32', reason="Requires symlinks")
def test_visit_directory_tree_follow_dirs(noncyclical_dir_structure):
| 66 | 67 | 224 | 32 | 34 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_visit_directory_tree_follow_dirs | test_visit_directory_tree_follow_dirs | 821 | 848 | 821 | 822 | cdc12e4ff8b868c95b53a7adf0d9e3467203bdd8 | bigcode/the-stack | train |
5951122033353fc6d250f715 | train | function | @pytest.mark.skipif(sys.platform == 'win32', reason="Requires symlinks")
def test_visit_directory_tree_follow_none(noncyclical_dir_structure):
root = str(noncyclical_dir_structure)
visitor = RegisterVisitor(root, follow_dirs=False, follow_symlink_dirs=False)
fs.visit_directory_tree(root, visitor)
j = os... | @pytest.mark.skipif(sys.platform == 'win32', reason="Requires symlinks")
def test_visit_directory_tree_follow_none(noncyclical_dir_structure):
| root = str(noncyclical_dir_structure)
visitor = RegisterVisitor(root, follow_dirs=False, follow_symlink_dirs=False)
fs.visit_directory_tree(root, visitor)
j = os.path.join
assert visitor.files == [
j('file_3'),
]
assert visitor.dirs_before == [
j('a'),
j('c'),
]
... | mlinked_dirs_before == [
j('a', 'to_c'),
j('b'),
]
assert not visitor.symlinked_dirs_after
@pytest.mark.skipif(sys.platform == 'win32', reason="Requires symlinks")
def test_visit_directory_tree_follow_none(noncyclical_dir_structure):
| 64 | 64 | 146 | 32 | 31 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_visit_directory_tree_follow_none | test_visit_directory_tree_follow_none | 851 | 868 | 851 | 852 | 70626b71b3299837d4de0bf71abe3ab2f4a4ba59 | bigcode/the-stack | train |
c85e3f4f7534812b5d137e3f | train | function | def test_headers_directory_setter():
if sys.platform == "win32":
root = r'C:\pfx\include\subdir'
else:
root = "/pfx/include/subdir"
hl = fs.HeaderList(
[root + '/foo.h', root + '/bar.h']
)
# Set directories using a list
hl.directories = [root]
assert hl.directories =... | def test_headers_directory_setter():
| if sys.platform == "win32":
root = r'C:\pfx\include\subdir'
else:
root = "/pfx/include/subdir"
hl = fs.HeaderList(
[root + '/foo.h', root + '/bar.h']
)
# Set directories using a list
hl.directories = [root]
assert hl.directories == [root]
# If it's a single dire... | /subdir/foo.h'],
['/pfx/include', '/pfx/subdir'])
]
@pytest.mark.parametrize('list_of_headers,expected_directories', dir_list)
def test_computation_of_header_directories(
list_of_headers, expected_directories
):
hl = fs.HeaderList(list_of_headers)
assert hl.directories == expected_directo... | 81 | 81 | 270 | 7 | 73 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_headers_directory_setter | test_headers_directory_setter | 409 | 442 | 409 | 409 | cf444424394a254e0e18a10c80992363302effbc | bigcode/the-stack | train |
072368b49e3c0403e332e0cc | train | function | @pytest.fixture()
def stage(tmpdir_factory):
"""Creates a stage with the directory structure for the tests."""
s = tmpdir_factory.mktemp('filesystem_test')
with s.as_cwd():
# Create source file hierarchy
fs.touchp('source/1')
fs.touchp('source/a/b/2')
fs.touchp('source/a/b/... | @pytest.fixture()
def stage(tmpdir_factory):
| """Creates a stage with the directory structure for the tests."""
s = tmpdir_factory.mktemp('filesystem_test')
with s.as_cwd():
# Create source file hierarchy
fs.touchp('source/1')
fs.touchp('source/a/b/2')
fs.touchp('source/a/b/3')
fs.touchp('source/c/4')
f... | MIT)
"""Tests for ``llnl/util/filesystem.py``"""
import os
import shutil
import stat
import sys
import pytest
import llnl.util.filesystem as fs
from llnl.util.symlink import islink, symlink
import spack.paths
@pytest.fixture()
def stage(tmpdir_factory):
| 67 | 67 | 224 | 9 | 57 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | stage | stage | 20 | 47 | 20 | 21 | ccd2f10e8890c8c85abea41e3a8a44d52d79f868 | bigcode/the-stack | train |
c367613a4a9b348a7c1a85ba | train | function | def test_paths_containing_libs(dirs_with_libfiles):
lib_to_dirs, all_dirs = dirs_with_libfiles
assert (set(fs.paths_containing_libs(all_dirs, ['libgfortran'])) ==
set(lib_to_dirs['libgfortran']))
assert (set(fs.paths_containing_libs(all_dirs, ['libirc'])) ==
set(lib_to_dirs['libirc... | def test_paths_containing_libs(dirs_with_libfiles):
| lib_to_dirs, all_dirs = dirs_with_libfiles
assert (set(fs.paths_containing_libs(all_dirs, ['libgfortran'])) ==
set(lib_to_dirs['libgfortran']))
assert (set(fs.paths_containing_libs(all_dirs, ['libirc'])) ==
set(lib_to_dirs['libirc']))
| Test source as a parent directory of destination."""
with fs.working_dir(str(stage)):
match = 'Cannot copy ancestor directory'
with pytest.raises(ValueError, match=match):
fs.install_tree('source', 'source/sub/directory')
def test_paths_containing_libs(dirs_with_libfiles... | 64 | 64 | 85 | 13 | 51 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_paths_containing_libs | test_paths_containing_libs | 309 | 316 | 309 | 309 | 066177924a8faa841038ea710af8390dd22b4551 | bigcode/the-stack | train |
317590e1468abbe3ed7136cd | train | function | def test_temporary_dir_context_manager():
previous_dir = os.path.realpath(os.getcwd())
with fs.temporary_dir() as tmp_dir:
assert previous_dir != os.path.realpath(os.getcwd())
assert os.path.realpath(str(tmp_dir)) == os.path.realpath(os.getcwd())
| def test_temporary_dir_context_manager():
| previous_dir = os.path.realpath(os.getcwd())
with fs.temporary_dir() as tmp_dir:
assert previous_dir != os.path.realpath(os.getcwd())
assert os.path.realpath(str(tmp_dir)) == os.path.realpath(os.getcwd())
| file2.remove()
# Assert that the modifications took place the modification time has not
# changed;
assert file1.read().strip() == 'file1'
assert not file2.exists()
assert int(mtime1) == int(file1.mtime())
def test_temporary_dir_context_manager():
| 64 | 64 | 60 | 8 | 56 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | test_temporary_dir_context_manager | test_temporary_dir_context_manager | 672 | 676 | 672 | 672 | 98d4d117322a54e1b496db781dbb2f467d1fc95f | bigcode/the-stack | train |
dea2b74b4b3b19e9589b355d | train | class | class TestCopy:
"""Tests for ``filesystem.copy``"""
def test_file_dest(self, stage):
"""Test using a filename as the destination."""
with fs.working_dir(str(stage)):
fs.copy('source/1', 'dest/1')
assert os.path.exists('dest/1')
def test_dir_dest(self, stage):
... | class TestCopy:
| """Tests for ``filesystem.copy``"""
def test_file_dest(self, stage):
"""Test using a filename as the destination."""
with fs.working_dir(str(stage)):
fs.copy('source/1', 'dest/1')
assert os.path.exists('dest/1')
def test_dir_dest(self, stage):
"""Test usin... | fs.touchp('source/g/h/i/9')
fs.touchp('source/g/i/j/10')
# Create symlinks
symlink(os.path.abspath('source/1'), 'source/2')
symlink('b/2', 'source/a/b2')
symlink('a/b', 'source/f')
# Create destination directory
fs.mkdirp('dest')
yield s
class TestCopy:
| 92 | 92 | 309 | 4 | 87 | FJ-NaokiMatsumura/spack | lib/spack/spack/test/llnl/util/filesystem.py | Python | TestCopy | TestCopy | 50 | 92 | 50 | 50 | d196e928a43b6d527ba4cf5306af28d57966e27e | bigcode/the-stack | train |
5f788b1ac60a7ba645b3da98 | train | function | def image_preprocessing(image_buffer, bbox, train, thread_id=0):
"""Decode and preprocess one image for evaluation or training.
Args:
image_buffer: JPEG encoded string Tensor
bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]
where each coordinate is [0, 1) and the coordinates a... | def image_preprocessing(image_buffer, bbox, train, thread_id=0):
| """Decode and preprocess one image for evaluation or training.
Args:
image_buffer: JPEG encoded string Tensor
bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]
where each coordinate is [0, 1) and the coordinates are arranged as
[ymin, xmin, ymax, xmax].
train: boolean... | 0.875)
image = tf.expand_dims(image, 0)
image = tf.compat.v1.image.resize_bilinear(image, [height, width],
align_corners=False)
image = tf.squeeze(image, [0])
return image
def image_preprocessing(image_buffer, bbox, train, thread_id=0):
| 70 | 70 | 235 | 16 | 53 | slabbaki/discriminative-subtyping | cen/data/tcga_dataset/Dataset_withAug.py | Python | image_preprocessing | image_preprocessing | 81 | 112 | 81 | 81 | 310f7f8dc2e98a8fab5c94de82d533015aa31ce5 | bigcode/the-stack | train |
6c441c77b0eee86907958a74 | train | function | def distort_color(image, thread_id=0, scope=None):
"""Distort the color of the image.
Each color distortion is non-commutative and thus ordering of the color ops
matters. Ideally we would randomly permute the ordering of the color ops.
Rather then adding that level of complication, we select a distinct orderin... | def distort_color(image, thread_id=0, scope=None):
| """Distort the color of the image.
Each color distortion is non-commutative and thus ordering of the color ops
matters. Ideally we would randomly permute the ordering of the color ops.
Rather then adding that level of complication, we select a distinct ordering
of color ops for each preprocessing thread.
... | from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
def decode_jpeg(image_buffer, scope=None):
with tf.compat.v1.keras.backend.name_scope(values=[image_buffer], name=scope,
default_name='decode_jpeg'):
image = tf.compat.v1.image.... | 115 | 115 | 384 | 13 | 101 | slabbaki/discriminative-subtyping | cen/data/tcga_dataset/Dataset_withAug.py | Python | distort_color | distort_color | 16 | 46 | 16 | 16 | b7283c002502c326f2c1c8c3a437f70232e0afac | bigcode/the-stack | train |
88d5289bebc62a25da0a138a | train | function | def decode_jpeg(image_buffer, scope=None):
with tf.compat.v1.keras.backend.name_scope(values=[image_buffer], name=scope,
default_name='decode_jpeg'):
image = tf.compat.v1.image.decode_jpeg(image_buffer, channels=3)
image = tf.compat.v1.image.convert_image_dtype(image, dtype=tf.float32)
... | def decode_jpeg(image_buffer, scope=None):
| with tf.compat.v1.keras.backend.name_scope(values=[image_buffer], name=scope,
default_name='decode_jpeg'):
image = tf.compat.v1.image.decode_jpeg(image_buffer, channels=3)
image = tf.compat.v1.image.convert_image_dtype(image, dtype=tf.float32)
return image
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
def decode_jpeg(image_buffer, scope=None):
| 43 | 64 | 77 | 10 | 32 | slabbaki/discriminative-subtyping | cen/data/tcga_dataset/Dataset_withAug.py | Python | decode_jpeg | decode_jpeg | 9 | 14 | 9 | 9 | a4c7deebc29a05f30d3b4235b6f9590c4c6f9160 | bigcode/the-stack | train |
af3128e31ae807064439514c | train | function | def parse_example_proto(example_serialized, train, num_preprocess_threads):
feature_map = {
'image/encoded': tf.io.FixedLenFeature([], dtype=tf.string,
default_value=''),
'image/class/label': tf.io.FixedLenFeature([1], dtype=tf.int64,
... | def parse_example_proto(example_serialized, train, num_preprocess_threads):
| feature_map = {
'image/encoded': tf.io.FixedLenFeature([], dtype=tf.string,
default_value=''),
'image/class/label': tf.io.FixedLenFeature([1], dtype=tf.int64,
default_value=-1),
'image/class/text': tf... | Error: if user does not provide bounding box
"""
if bbox is None:
raise ValueError('Please supply a bounding box.')
image = decode_jpeg(image_buffer)
height = 299
width = 299
if train:
image = distort_image(image, height, width, bbox, thread_id)
else:
image = eval_image(image, height, width)... | 127 | 127 | 426 | 15 | 111 | slabbaki/discriminative-subtyping | cen/data/tcga_dataset/Dataset_withAug.py | Python | parse_example_proto | parse_example_proto | 116 | 158 | 116 | 117 | 04186831a2828565261fd8d1fa8283d31c988799 | bigcode/the-stack | train |
7051ff230f562099271dd502 | train | function | def tfrecord_train_input_fn(train, path, batch_size=128, num_preprocess_threads=None, epochs=None):
dataset = tf.data.TFRecordDataset(path)
with tf.device('/cpu:0'):
if train:
dataset = dataset.map(lambda x:parse_example_proto(x, train, num_preprocess_threads)).shuffle(True).batch(batc... | def tfrecord_train_input_fn(train, path, batch_size=128, num_preprocess_threads=None, epochs=None):
| dataset = tf.data.TFRecordDataset(path)
with tf.device('/cpu:0'):
if train:
dataset = dataset.map(lambda x:parse_example_proto(x, train, num_preprocess_threads)).shuffle(True).batch(batch_size).repeat(epochs)
else:
dataset = dataset.map(lambda x:parse_example_prot... | 3
img = tf.keras.backend.cast(img, tf.float32)
img = tf.reshape(img, shape=[height, width, depth])
return img, label[0,:]
def tfrecord_train_input_fn(train, path, batch_size=128, num_preprocess_threads=None, epochs=None):
| 64 | 64 | 116 | 24 | 40 | slabbaki/discriminative-subtyping | cen/data/tcga_dataset/Dataset_withAug.py | Python | tfrecord_train_input_fn | tfrecord_train_input_fn | 160 | 167 | 160 | 160 | 517be7e5422c56382b9c556bdee136c70cdf0c9c | bigcode/the-stack | train |
4d0e24718c5e18e0fd084dfb | train | function | def eval_image(image, height, width, scope=None):
with tf.compat.v1.keras.backend.name_scope(values=[image, height, width], name=scope,
default_name='eval_image'):
image = tf.compat.v1.image.central_crop(image, central_fraction=0.875)
image = tf.expand_dims(image, 0)
image = tf.compa... | def eval_image(image, height, width, scope=None):
| with tf.compat.v1.keras.backend.name_scope(values=[image, height, width], name=scope,
default_name='eval_image'):
image = tf.compat.v1.image.central_crop(image, central_fraction=0.875)
image = tf.expand_dims(image, 0)
image = tf.compat.v1.image.resize_bilinear(image, [height, width],
... | =resize_method)
distorted_image.set_shape([height, width, 3])
distorted_image = tf.compat.v1.image.random_flip_left_right(distorted_image)
distorted_image = distort_color(distorted_image, thread_id)
return distorted_image
def eval_image(image, height, width, scope=None):
| 64 | 64 | 110 | 12 | 51 | slabbaki/discriminative-subtyping | cen/data/tcga_dataset/Dataset_withAug.py | Python | eval_image | eval_image | 70 | 79 | 70 | 71 | 48b676cc22025cbc61024e57c7f9c77f531eb88f | bigcode/the-stack | train |
42959778dbeb6240e21f1c28 | train | function | def distort_image(image, height, width, bbox, thread_id=0, scope=None):
sample_distorted_bounding_box = tf.compat.v1.image.sample_distorted_bounding_box(
tf.shape(image),
bounding_boxes=bbox,
min_object_covered=0.1,
aspect_ratio_range=[0.75, 1.33],
area_range=[0.05, 1.0]... | def distort_image(image, height, width, bbox, thread_id=0, scope=None):
| sample_distorted_bounding_box = tf.compat.v1.image.sample_distorted_bounding_box(
tf.shape(image),
bounding_boxes=bbox,
min_object_covered=0.1,
aspect_ratio_range=[0.75, 1.33],
area_range=[0.05, 1.0],
max_attempts=100,
use_image_if_no_bounding_boxes=True)
... | image = tf.compat.v1.image.random_hue(image, max_delta=0.2)
image = tf.compat.v1.clip_by_value(image, 0.0, 1.0)
return image
def distort_image(image, height, width, bbox, thread_id=0, scope=None):
| 65 | 65 | 218 | 20 | 44 | slabbaki/discriminative-subtyping | cen/data/tcga_dataset/Dataset_withAug.py | Python | distort_image | distort_image | 48 | 68 | 48 | 49 | d6ec27f2c1b61a47c02e6dbee8a43509aaf9b843 | bigcode/the-stack | train |
428ab575bc9993afbc962b06 | train | class | class ArangoFilter:
def __init__(self, name, op, var):
self.vars = {}
self.expression = ''
self.or_ = False
self.prepend = True
self.rec_name = None
getattr(self, op)(name, var)
def eq(self, name: str, var):
v = name.replace('.', '_')
self.express... | class ArangoFilter:
| def __init__(self, name, op, var):
self.vars = {}
self.expression = ''
self.or_ = False
self.prepend = True
self.rec_name = None
getattr(self, op)(name, var)
def eq(self, name: str, var):
v = name.replace('.', '_')
self.expression = '{0}==@{1}'.fo... | from arorm.databases.arango.query import ArangoStoreQuery
class ArangoFilter:
| 19 | 172 | 576 | 5 | 13 | patricklx/ar-orm | arorm/databases/arango/filter.py | Python | ArangoFilter | ArangoFilter | 4 | 63 | 4 | 4 | 1d8717c348ce461558f735581bb48f4d0a68cdc6 | bigcode/the-stack | train |
8318bfa5f37e9fc3e31d7175 | train | function | def filter(self, *args, **kwargs):
for a in args:
if isinstance(a, ArangoFilter):
old_filter(self, a.expression, a.or_ or kwargs.get('_or', False), a.prepend, a.rec_name, **a.vars)
else:
old_filter(self, a, **kwargs)
return self
| def filter(self, *args, **kwargs):
| for a in args:
if isinstance(a, ArangoFilter):
old_filter(self, a.expression, a.or_ or kwargs.get('_or', False), a.prepend, a.rec_name, **a.vars)
else:
old_filter(self, a, **kwargs)
return self
| '_')
self.expression = f'rec.{name}.{sub_name} == @{v}_val'
self.vars[v+'_val'] = isinstance(val, ArangoStoreQuery) and val._make_aql() or val
self.prepend = False
def filter(self, *args, **kwargs):
| 64 | 64 | 73 | 10 | 53 | patricklx/ar-orm | arorm/databases/arango/filter.py | Python | filter | filter | 66 | 72 | 66 | 66 | eafd96151b7eaba8b89d58fd27f5724ce492a914 | bigcode/the-stack | train |
8761a3af0fb6cf1fd474427c | train | function | def set_default_value(config, key, value):
if key not in config:
config[key] = value
| def set_default_value(config, key, value):
| if key not in config:
config[key] = value
| MIT)
# See license file or visit www.open3d.org for details
# examples/python/reconstruction_system/initialize_config.py
import os
import sys
sys.path.append("./reconstruction/utility")
from file import check_folder_structure, extract_rgbd_frames
def set_default_value(config, key, value):
| 64 | 64 | 24 | 10 | 53 | yutashx/PiSense | reconstruction/reconstruction_system/initialize_config.py | Python | set_default_value | set_default_value | 13 | 15 | 13 | 13 | 3bd76a7ad36b6d11be51ef8ed9a94702148e801d | bigcode/the-stack | train |
24008439c70607616c23cf71 | train | function | def initialize_config(config):
# set default parameters if not specified
set_default_value(config, "depth_map_type", "redwood")
set_default_value(config, "n_frames_per_fragment", 100)
set_default_value(config, "n_keyframes_per_n_frame", 5)
set_default_value(config, "min_depth", 0.3)
set_default... | def initialize_config(config):
# set default parameters if not specified
| set_default_value(config, "depth_map_type", "redwood")
set_default_value(config, "n_frames_per_fragment", 100)
set_default_value(config, "n_keyframes_per_n_frame", 5)
set_default_value(config, "min_depth", 0.3)
set_default_value(config, "max_depth", 3.0)
set_default_value(config, "voxel_size", 0... | # Open3D: www.open3d.org
# The MIT License (MIT)
# See license file or visit www.open3d.org for details
# examples/python/reconstruction_system/initialize_config.py
import os
import sys
sys.path.append("./reconstruction/utility")
from file import check_folder_structure, extract_rgbd_frames
def set_default_value(con... | 108 | 238 | 794 | 14 | 93 | yutashx/PiSense | reconstruction/reconstruction_system/initialize_config.py | Python | initialize_config | initialize_config | 18 | 79 | 18 | 20 | c6650e2e8184ffdac14dd01545c854427f599714 | bigcode/the-stack | train |
5601a817e66094a11b7cf843 | train | function | @log.call(skip_args=["text"])
def view_text(text: str):
file = file_sys.get_tmp_location("text_view.txt")
file_sys.write_text(text=text, file=file)
view_file(file, safe=True)
| @log.call(skip_args=["text"])
def view_text(text: str):
| file = file_sys.get_tmp_location("text_view.txt")
file_sys.write_text(text=text, file=file)
view_file(file, safe=True)
| return ["xdg-open"]
raise OSError("Unsupported os")
process = Process(target=partial(call, get_view_cmd() + [str(path)]))
process.start()
process.join(timeout=5)
return path
@log.call(skip_args=["text"])
def view_text(text: str):
| 64 | 64 | 47 | 15 | 48 | nachereshata/HedUtils | src/hed_utils/support/os_util.py | Python | view_text | view_text | 183 | 187 | 183 | 184 | 3c4ec741f1ffe2f9a5b41ef09cd0fe092d4d2fa3 | bigcode/the-stack | train |
7afbd245628d0e46b75ddfe1 | train | function | @log.call
def view_file(path, safe=False):
from multiprocessing import Process
from subprocess import call
from functools import partial
path = (path if isinstance(path, Path) else Path(path)).absolute()
if not path.exists():
raise FileNotFoundError(path)
if safe:
path = file_... | @log.call
def view_file(path, safe=False):
| from multiprocessing import Process
from subprocess import call
from functools import partial
path = (path if isinstance(path, Path) else Path(path)).absolute()
if not path.exists():
raise FileNotFoundError(path)
if safe:
path = file_sys.copy_to_tmp(path)
@log.call
de... | if pattern is not None:
victims.extend(kill_process_by_pattern(pattern, ignorecase=ignorecase, dry=dry))
if pid is not None:
victims.extend(kill_process_by_pid(pid, dry=dry))
return victims
@log.call
def view_file(path, safe=False):
| 64 | 64 | 154 | 12 | 51 | nachereshata/HedUtils | src/hed_utils/support/os_util.py | Python | view_file | view_file | 151 | 180 | 151 | 152 | 8bb0b03dd3c70584759af2350d1798e6a15c017f | bigcode/the-stack | train |
7e89070918603bfc9f02d280 | train | function | @log.call(log_result=False)
def kill_all(*, name=None, pattern=None, pid=None, ignorecase=False, dry=False) -> List[KillVictim]:
victims = []
if name is not None:
victims.extend(kill_process_by_name(name, ignorecase=ignorecase, dry=dry))
if pattern is not None:
victims.extend(kill_process_... | @log.call(log_result=False)
def kill_all(*, name=None, pattern=None, pid=None, ignorecase=False, dry=False) -> List[KillVictim]:
| victims = []
if name is not None:
victims.extend(kill_process_by_name(name, ignorecase=ignorecase, dry=dry))
if pattern is not None:
victims.extend(kill_process_by_pattern(pattern, ignorecase=ignorecase, dry=dry))
if pid is not None:
victims.extend(kill_process_by_pid(pid, dry... | (re.findall(pattern, process_name))
if should_kill:
victims.extend(_rkill(process, dry=dry))
return victims
@log.call(log_result=False)
def kill_all(*, name=None, pattern=None, pid=None, ignorecase=False, dry=False) -> List[KillVictim]:
| 64 | 64 | 118 | 35 | 28 | nachereshata/HedUtils | src/hed_utils/support/os_util.py | Python | kill_all | kill_all | 135 | 148 | 135 | 136 | 9579b23c5fb4146cf973f63e62930ce246d6bfd0 | bigcode/the-stack | train |
4dd1f6b094b1584d3acc92de | train | function | @log.call
def kill_process_by_pid(pid, dry=True) -> List[KillVictim]:
if not pid:
raise ValueError(f"pid not set! ({pid})")
return _rkill(psutil.Process(pid=int(pid)), dry=dry)
| @log.call
def kill_process_by_pid(pid, dry=True) -> List[KillVictim]:
| if not pid:
raise ValueError(f"pid not set! ({pid})")
return _rkill(psutil.Process(pid=int(pid)), dry=dry)
| .process_iter():
process_name = process.name().lower() if ignorecase else process.name()
if process_name == target_name:
victims.extend(_rkill(process, dry=dry))
return victims
@log.call
def kill_process_by_pid(pid, dry=True) -> List[KillVictim]:
| 64 | 64 | 56 | 21 | 42 | nachereshata/HedUtils | src/hed_utils/support/os_util.py | Python | kill_process_by_pid | kill_process_by_pid | 105 | 109 | 105 | 106 | 47163d2d4b5b9615669bbcbfd07f088e84456bc2 | bigcode/the-stack | train |
652d15728485e74cead1fe53 | train | function | @log.call
def kill_process_by_pattern(pattern: str, ignorecase=False, dry=True) -> List[KillVictim]:
if not pattern:
raise ValueError(f"pattern not set!({pattern})")
if not isinstance(pattern, str):
raise TypeError(f"pattern must be str! ({type(pattern).__name__}) {pattern}")
victims = []
... | @log.call
def kill_process_by_pattern(pattern: str, ignorecase=False, dry=True) -> List[KillVictim]:
| if not pattern:
raise ValueError(f"pattern not set!({pattern})")
if not isinstance(pattern, str):
raise TypeError(f"pattern must be str! ({type(pattern).__name__}) {pattern}")
victims = []
for process in psutil.process_iter():
process_name = process.name()
if ignorecas... | im]:
if not pid:
raise ValueError(f"pid not set! ({pid})")
return _rkill(psutil.Process(pid=int(pid)), dry=dry)
@log.call
def kill_process_by_pattern(pattern: str, ignorecase=False, dry=True) -> List[KillVictim]:
| 64 | 64 | 157 | 27 | 37 | nachereshata/HedUtils | src/hed_utils/support/os_util.py | Python | kill_process_by_pattern | kill_process_by_pattern | 112 | 132 | 112 | 113 | 2257b32688896a2dcff43a08219fe88a777fce3a | bigcode/the-stack | train |
9704c0224c046f073f5d7372 | train | function | @log.call
def _kill(process: psutil.Process, timeout=5) -> bool:
"""Attempts to kill the process in a fail-safe manner and returns status
Tries to terminate the process first and waits for it for the given timeout.
If termination fails - attempts to kill the process instead and wait for it to die.
Arg... | @log.call
def _kill(process: psutil.Process, timeout=5) -> bool:
| """Attempts to kill the process in a fail-safe manner and returns status
Tries to terminate the process first and waits for it for the given timeout.
If termination fails - attempts to kill the process instead and wait for it to die.
Args:
process(Process): the process that is to be killed
... | Windows"
IS_LINUX = platform.system() == "Linux"
IS_MAC = platform.system() in ("Darwin", "macosx")
IS_64BITS = sys.maxsize > 2 ** 32
@log.call
def _kill(process: psutil.Process, timeout=5) -> bool:
| 64 | 64 | 205 | 20 | 43 | nachereshata/HedUtils | src/hed_utils/support/os_util.py | Python | _kill | _kill | 28 | 62 | 28 | 29 | b8ed0d429a84ba410dafa56c307da6fd9a167d9c | bigcode/the-stack | train |
8afe832308f42b3dbaab4a66 | train | function | @log.call(skip_args=["victims"], log_result=False)
def _rkill(process: psutil.Process, *, dry=True) -> List[KillVictim]:
victims = []
if process.is_running():
with process.oneshot():
ppid = process.ppid()
pid = process.pid
name = process.name()
for child_p... | @log.call(skip_args=["victims"], log_result=False)
def _rkill(process: psutil.Process, *, dry=True) -> List[KillVictim]:
| victims = []
if process.is_running():
with process.oneshot():
ppid = process.ppid()
pid = process.pid
name = process.name()
for child_process in process.children(recursive=True):
victims.extend(_rkill(child_process, dry=dry))
victims.a... | try:
process.wait(timeout)
return True
except:
pass
except:
pass
return not process.is_running()
@log.call(skip_args=["victims"], log_result=False)
def _rkill(process: psutil.Process, *, dry=True) -> List[KillVictim]:
| 64 | 64 | 124 | 34 | 30 | nachereshata/HedUtils | src/hed_utils/support/os_util.py | Python | _rkill | _rkill | 65 | 82 | 65 | 66 | d1d7cbf570906d762f71554424b3c31a94fb2f54 | bigcode/the-stack | train |
1b7dcbb3742ec248106ed22a | train | function | @log.call
def kill_process_by_name(name: str, *, ignorecase=False, dry=True) -> List[KillVictim]:
if not name:
raise ValueError(f"name not set!({name})")
if not isinstance(name, str):
raise TypeError(f"name must be str! ({name})")
victims = []
target_name = name.lower() if ignorecase e... | @log.call
def kill_process_by_name(name: str, *, ignorecase=False, dry=True) -> List[KillVictim]:
| if not name:
raise ValueError(f"name not set!({name})")
if not isinstance(name, str):
raise TypeError(f"name must be str! ({name})")
victims = []
target_name = name.lower() if ignorecase else name
for process in psutil.process_iter():
process_name = process.name().lower() ... | _process, dry=dry))
victims.append(KillVictim(ppid, pid, name, ("SKIPPED" if dry else _kill(process))))
return victims
@log.call
def kill_process_by_name(name: str, *, ignorecase=False, dry=True) -> List[KillVictim]:
| 64 | 64 | 134 | 28 | 35 | nachereshata/HedUtils | src/hed_utils/support/os_util.py | Python | kill_process_by_name | kill_process_by_name | 85 | 102 | 85 | 86 | 64d8a93cbad1d543c81c47650ba5ea4e1b766e69 | bigcode/the-stack | train |
a3365edb4bcabc1d51a78e7f | train | class | @register_op
class LetterBoxResize(BaseOperator):
def __init__(self, target_size):
"""
Resize image to target size, convert normalized xywh to pixel xyxy
format ([x_center, y_center, width, height] -> [x0, y0, x1, y1]).
Args:
target_size (int|list): image target size.
... | @register_op
class LetterBoxResize(BaseOperator):
| def __init__(self, target_size):
"""
Resize image to target size, convert normalized xywh to pixel xyxy
format ([x_center, y_center, width, height] -> [x0, y0, x1, y1]).
Args:
target_size (int|list): image target size.
"""
super(LetterBoxResize, self).__in... | _function
try:
from collections.abc import Sequence
except Exception:
from collections import Sequence
from numbers import Integral
import cv2
import copy
import numpy as np
import random
import math
from .operators import BaseOperator, register_op
from .batch_operators import Gt2TTFTarget
from paddlex.ppdet... | 256 | 256 | 863 | 11 | 244 | cheneyveron/PaddleX | paddlex/ppdet/data/transform/mot_operators.py | Python | LetterBoxResize | LetterBoxResize | 58 | 130 | 58 | 59 | 8ca8ba1a5861fb8816134e6f62765d7e32cc5490 | bigcode/the-stack | train |
1607bd0befd7e50f7ada5d8d | train | class | @register_op
class MOTRandomAffine(BaseOperator):
"""
Affine transform to image and coords to achieve the rotate, scale and
shift effect for training image.
Args:
degrees (list[2]): the rotate range to apply, transform range is [min, max]
translate (list[2]): the translate range to appl... | @register_op
class MOTRandomAffine(BaseOperator):
| """
Affine transform to image and coords to achieve the rotate, scale and
shift effect for training image.
Args:
degrees (list[2]): the rotate range to apply, transform range is [min, max]
translate (list[2]): the translate range to apply, transform range is [min, max]
scale (li... | ):
""" Resize the image numpy.
"""
im = sample['image']
h, w = sample['im_shape']
if not isinstance(im, np.ndarray):
raise TypeError("{}: image type is not numpy.".format(self))
if len(im.shape) != 3:
from PIL import UnidentifiedImageError
... | 256 | 256 | 1,517 | 11 | 244 | cheneyveron/PaddleX | paddlex/ppdet/data/transform/mot_operators.py | Python | MOTRandomAffine | MOTRandomAffine | 133 | 263 | 133 | 134 | 9b4783ee2b9cde957fa8cb51c407daa022e325fe | bigcode/the-stack | train |
0b421543db9a1d2b61195a6a | train | class | class Gt2FairMOTTarget(Gt2TTFTarget):
__shared__ = ['num_classes']
"""
Generate FairMOT targets by ground truth data.
Difference between Gt2FairMOTTarget and Gt2TTFTarget are:
1. the gaussian kernal radius to generate a heatmap.
2. the targets needed during traing.
Args:
num... | class Gt2FairMOTTarget(Gt2TTFTarget):
| __shared__ = ['num_classes']
"""
Generate FairMOT targets by ground truth data.
Difference between Gt2FairMOTTarget and Gt2TTFTarget are:
1. the gaussian kernal radius to generate a heatmap.
2. the targets needed during traing.
Args:
num_classes(int): the number of classes.
... | gwh = t_box[:, 0:2].copy(), t_box[:, 2:4].copy()
gxy[:, 0] = gxy[:, 0] * nGw
gxy[:, 1] = gxy[:, 1] * nGh
gwh[:, 0] = gwh[:, 0] * nGw
gwh[:, 1] = gwh[:, 1] * nGh
# XY coordinates
tbox[:, :, :, 0:2][a... | 256 | 256 | 1,230 | 15 | 240 | cheneyveron/PaddleX | paddlex/ppdet/data/transform/mot_operators.py | Python | Gt2FairMOTTarget | Gt2FairMOTTarget | 527 | 628 | 527 | 527 | 0ae6e4e24882cb012c7cf9c236c1631079a64611 | bigcode/the-stack | train |
51ff0a5928d3430a5a993489 | train | class | @register_op
class RGBReverse(BaseOperator):
"""RGB to BGR, or BGR to RGB, sensitive to MOTRandomAffine
"""
def __init__(self):
super(RGBReverse, self).__init__()
def apply(self, sample, context=None):
im = sample['image']
sample['image'] = np.ascontiguousarray(im[:, :, ::-1])
... | @register_op
class RGBReverse(BaseOperator):
| """RGB to BGR, or BGR to RGB, sensitive to MOTRandomAffine
"""
def __init__(self):
super(RGBReverse, self).__init__()
def apply(self, sample, context=None):
im = sample['image']
sample['image'] = np.ascontiguousarray(im[:, :, ::-1])
return sample
| = setup_logger(__name__)
__all__ = [
'RGBReverse', 'LetterBoxResize', 'MOTRandomAffine', 'Gt2JDETargetThres',
'Gt2JDETargetMax', 'Gt2FairMOTTarget'
]
@register_op
class RGBReverse(BaseOperator):
| 64 | 64 | 87 | 10 | 54 | cheneyveron/PaddleX | paddlex/ppdet/data/transform/mot_operators.py | Python | RGBReverse | RGBReverse | 44 | 55 | 44 | 45 | 79e5b21c221cd08140916278c3fb7d25efb3f4ee | bigcode/the-stack | train |
fb1a00a43c6811689f387b75 | train | class | @register_op
class Gt2JDETargetMax(BaseOperator):
__shared__ = ['num_classes']
"""
Generate JDE targets by groud truth data when evaluating
Args:
anchors (list): anchors of JDE model
anchor_masks (list): anchor_masks of JDE model
downsample_ratios (list): downsample ratios of JDE... | @register_op
class Gt2JDETargetMax(BaseOperator):
| __shared__ = ['num_classes']
"""
Generate JDE targets by groud truth data when evaluating
Args:
anchors (list): anchors of JDE model
anchor_masks (list): anchor_masks of JDE model
downsample_ratios (list): downsample ratios of JDE model
max_iou_thresh (float): iou thresh ... | _thresh
bg_index = iou_map < self.bg_thresh
ign_index = (iou_map < self.fg_thresh) * (
iou_map > self.bg_thresh)
tconf[fg_index] = 1
tconf[bg_index] = 0
tconf[ign_index] = -1
gt_index = gt_index_map[fg_i... | 256 | 256 | 1,143 | 15 | 240 | cheneyveron/PaddleX | paddlex/ppdet/data/transform/mot_operators.py | Python | Gt2JDETargetMax | Gt2JDETargetMax | 428 | 524 | 428 | 429 | 41d38fac066fb41a7a11b69899127ea763c1f289 | bigcode/the-stack | train |
d0f479a02f93a382439710a6 | train | class | @register_op
class Gt2JDETargetThres(BaseOperator):
__shared__ = ['num_classes']
"""
Generate JDE targets by groud truth data when training
Args:
anchors (list): anchors of JDE model
anchor_masks (list): anchor_masks of JDE model
downsample_ratios (list): downsample ratios of JDE... | @register_op
class Gt2JDETargetThres(BaseOperator):
| __shared__ = ['num_classes']
"""
Generate JDE targets by groud truth data when training
Args:
anchors (list): anchors of JDE model
anchor_masks (list): anchor_masks of JDE model
downsample_ratios (list): downsample ratios of JDE model
ide_thresh (float): thresh of identit... | [:, 2] - xy[:, 0]
h = xy[:, 3] - xy[:, 1]
area = w * h
ar = np.maximum(w / (h + 1e-16), h / (w + 1e-16))
i = (w > 4) & (h > 4) & (area / (area0 + 1e-16) > 0.1) & (ar < 10)
if sum(i) > 0:
sample['gt_bbox'] = xy[i].astype(sample['gt_bbox'].dtype... | 256 | 256 | 1,800 | 16 | 239 | cheneyveron/PaddleX | paddlex/ppdet/data/transform/mot_operators.py | Python | Gt2JDETargetThres | Gt2JDETargetThres | 266 | 425 | 266 | 267 | 807a1651d9217122258cee6e50a9be0760feb80a | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.