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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aa4fec80dcd1b883790632fe | train | function | def test_disksaver_wrong_input(dirname):
with pytest.raises(ValueError, match=r"Directory path '\S+' is not found"):
DiskSaver("/tmp/non-existing-folder", create_dir=False)
def _test(ext):
previous_fname = os.path.join(dirname, f"{_PREFIX}_obj_{1}{ext}")
with open(previous_fname, "w") ... | def test_disksaver_wrong_input(dirname):
| with pytest.raises(ValueError, match=r"Directory path '\S+' is not found"):
DiskSaver("/tmp/non-existing-folder", create_dir=False)
def _test(ext):
previous_fname = os.path.join(dirname, f"{_PREFIX}_obj_{1}{ext}")
with open(previous_fname, "w") as f:
f.write("test")
... | )
Checkpoint.load_objects(to_load_single_object, loaded_checkpoint, strict=False, blah="blah")
loaded_weights = to_load_single_object["pretrained_features"].state_dict()["weight"]
assert torch.all(model.state_dict()["features.weight"].eq(loaded_weights))
def test_disksaver_wrong_input(dirname):
| 64 | 64 | 119 | 9 | 55 | OBITORASU/ignite | tests/ignite/handlers/test_checkpoint.py | Python | test_disksaver_wrong_input | test_disksaver_wrong_input | 1,132 | 1,145 | 1,132 | 1,133 | fbf6784cb83a12912b1dce2b83a0e3babbd5c73e | bigcode/the-stack | train |
31354356f4ccd2b4570fb517 | train | function | def test_disk_saver_atomic(dirname):
model = DummyModel()
to_save_serializable = {"model": model}
to_save_non_serializable = {"model": lambda x: x}
def _test_existance(atomic, _to_save, expected):
saver = DiskSaver(dirname, atomic=atomic, create_dir=False, require_empty=False)
fname =... | def test_disk_saver_atomic(dirname):
| model = DummyModel()
to_save_serializable = {"model": model}
to_save_non_serializable = {"model": lambda x: x}
def _test_existance(atomic, _to_save, expected):
saver = DiskSaver(dirname, atomic=atomic, create_dir=False, require_empty=False)
fname = "test.pt"
try:
wi... | ModelCheckpoint(dirname, _PREFIX)
to_save = {"model": DummyModel()}
# Redefine save_handler
h.save_handler = lambda x, y: None
h(Engine(lambda x, y: None), to_save)
with pytest.raises(
RuntimeError, match=rf"Unable to save checkpoint, save_handler should be DiskSaver, got {type(h.save_hand... | 99 | 99 | 332 | 8 | 90 | OBITORASU/ignite | tests/ignite/handlers/test_checkpoint.py | Python | test_disk_saver_atomic | test_disk_saver_atomic | 578 | 611 | 578 | 579 | 8aca68b2f6f9983d6a1284fb9f22a9a29f02db99 | bigcode/the-stack | train |
5463b06a3bcab993a8f68786 | train | function | def test_with_state_dict(dirname):
def update_fn(_1, _2):
pass
engine = Engine(update_fn)
handler = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=1)
model = DummyModel()
to_save = {"model": model}
engine.add_event_handler(Events.EPOCH_COMPLETED, handler, to_save)
engi... | def test_with_state_dict(dirname):
| def update_fn(_1, _2):
pass
engine = Engine(update_fn)
handler = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=1)
model = DummyModel()
to_save = {"model": model}
engine.add_event_handler(Events.EPOCH_COMPLETED, handler, to_save)
engine.run([0, 1, 2], max_epochs=4)
... | )
engine.run([0, 1,], max_epochs=4)
expected = sorted([f"{_PREFIX}_{name}_{i}.pt" for i in [3 * 2, 4 * 2]])
assert sorted(os.listdir(dirname)) == expected
def test_with_state_dict(dirname):
| 64 | 64 | 205 | 7 | 56 | OBITORASU/ignite | tests/ignite/handlers/test_checkpoint.py | Python | test_with_state_dict | test_with_state_dict | 765 | 791 | 765 | 765 | dca69e132c62bd824dc775bd2452687ee9b2f163 | bigcode/the-stack | train |
158e426e46bcebcd4768a3bb | train | function | def _test_checkpoint_load_objects_ddp(device):
model = DummyModel().to(device)
device_ids = (
None if "cpu" in device.type else [device,]
)
ddp_model = nn.parallel.DistributedDataParallel(model, device_ids=device_ids)
opt = torch.optim.SGD(ddp_model.parameters(), lr=0.01)
# single objec... | def _test_checkpoint_load_objects_ddp(device):
| model = DummyModel().to(device)
device_ids = (
None if "cpu" in device.type else [device,]
)
ddp_model = nn.parallel.DistributedDataParallel(model, device_ids=device_ids)
opt = torch.optim.SGD(ddp_model.parameters(), lr=0.01)
# single object:
to_load = {"model": ddp_model}
check... | checkpointer(trainer)
assert save_handler.call_count == 1
metadata = {"basename": "model", "score_name": None, "priority": 0}
save_handler.assert_called_with(model.state_dict(), "model_0.pt", metadata)
def _test_checkpoint_load_objects_ddp(device):
| 64 | 64 | 163 | 10 | 54 | OBITORASU/ignite | tests/ignite/handlers/test_checkpoint.py | Python | _test_checkpoint_load_objects_ddp | _test_checkpoint_load_objects_ddp | 1,170 | 1,186 | 1,170 | 1,170 | 7c97fe5537cc1590b9e064205cf0f16234dd6fb2 | bigcode/the-stack | train |
e3a3d72f716c31307f4a62a5 | train | function | def test_save_model_optimizer_lr_scheduler_with_state_dict(dirname):
_test_save_model_optimizer_lr_scheduler_with_state_dict("cpu", dirname)
| def test_save_model_optimizer_lr_scheduler_with_state_dict(dirname):
| _test_save_model_optimizer_lr_scheduler_with_state_dict("cpu", dirname)
| in lr_scheduler_state_dict.keys():
assert key in loaded_lr_scheduler_state_dict
lr_scheduler_value = lr_scheduler_state_dict[key]
loaded_lr_scheduler_value = loaded_lr_scheduler_state_dict[key]
assert lr_scheduler_value == loaded_lr_scheduler_value
def test_save_model_optimizer_lr_sched... | 64 | 64 | 28 | 12 | 51 | OBITORASU/ignite | tests/ignite/handlers/test_checkpoint.py | Python | test_save_model_optimizer_lr_scheduler_with_state_dict | test_save_model_optimizer_lr_scheduler_with_state_dict | 893 | 894 | 893 | 893 | 25bddcfba756ac1fcb7a84c70b69ca6345c46431 | bigcode/the-stack | train |
f8ce4cf1933d44bdac825661 | train | function | def test_disk_saver_unknown_keyword(dirname):
model = DummyModel()
to_save = {"model": model}
saver = DiskSaver(dirname, create_dir=False, unknown_keyword="")
fname = "test.pt"
with pytest.raises(TypeError, match=r"got an unexpected keyword argument 'unknown_keyword'"):
saver(to_save, fname... | def test_disk_saver_unknown_keyword(dirname):
| model = DummyModel()
to_save = {"model": model}
saver = DiskSaver(dirname, create_dir=False, unknown_keyword="")
fname = "test.pt"
with pytest.raises(TypeError, match=r"got an unexpected keyword argument 'unknown_keyword'"):
saver(to_save, fname)
| DiskSaver(dirname, create_dir=False, _use_new_zipfile_serialization=False)
fname = "test.pt"
saver(to_save, fname)
fp = os.path.join(saver.dirname, fname)
assert os.path.exists(fp)
saver.remove(fname)
def test_disk_saver_unknown_keyword(dirname):
| 64 | 64 | 72 | 9 | 55 | OBITORASU/ignite | tests/ignite/handlers/test_checkpoint.py | Python | test_disk_saver_unknown_keyword | test_disk_saver_unknown_keyword | 629 | 636 | 629 | 629 | b6baba59ebabc6bd3ddf716b1fcc6f3d112ebff2 | bigcode/the-stack | train |
263970291eaeb955f9532fd2 | train | function | def test_checkpoint_save_handler_callable():
def save_handler(c, f):
assert f == "model_12.pt"
to_save = {"model": DummyModel()}
checkpointer = Checkpoint(to_save, save_handler=save_handler,)
trainer = Engine(lambda e, b: None)
trainer.state = State(epoch=1, iteration=12)
checkpointe... | def test_checkpoint_save_handler_callable():
| def save_handler(c, f):
assert f == "model_12.pt"
to_save = {"model": DummyModel()}
checkpointer = Checkpoint(to_save, save_handler=save_handler,)
trainer = Engine(lambda e, b: None)
trainer.state = State(epoch=1, iteration=12)
checkpointer(trainer)
| .1
trainer.state = State(epoch=1, iteration=i, metrics={"val_acc": val_acc})
checkpointer(trainer)
assert save_handler.call_count == 10
assert checkpointer.last_checkpoint == "model_val_acc=0.9000.pt"
def test_checkpoint_save_handler_callable():
| 64 | 64 | 82 | 7 | 57 | OBITORASU/ignite | tests/ignite/handlers/test_checkpoint.py | Python | test_checkpoint_save_handler_callable | test_checkpoint_save_handler_callable | 478 | 489 | 478 | 478 | 7dc5468dbd2751e763a69ce94eb9660055cf2645 | bigcode/the-stack | train |
88049c385bf2dcfd66fbeefa | train | function | def test_checkpoint_state_dict():
checkpointer = _setup_checkpoint()
sd = checkpointer.state_dict()
assert "saved" in sd
assert isinstance(sd["saved"], list) and len(sd["saved"]) == len(checkpointer._saved)
for saved_item, true_item in zip(sd["saved"], checkpointer._saved):
assert saved_ite... | def test_checkpoint_state_dict():
| checkpointer = _setup_checkpoint()
sd = checkpointer.state_dict()
assert "saved" in sd
assert isinstance(sd["saved"], list) and len(sd["saved"]) == len(checkpointer._saved)
for saved_item, true_item in zip(sd["saved"], checkpointer._saved):
assert saved_item[0] == true_item.priority
... | =0, iteration=0)
checkpointer(trainer)
trainer.state.iteration = 10
checkpointer(trainer)
trainer.state.iteration = 20
checkpointer(trainer)
assert save_handler.call_count == 3
return checkpointer
def test_checkpoint_state_dict():
| 64 | 64 | 94 | 6 | 57 | OBITORASU/ignite | tests/ignite/handlers/test_checkpoint.py | Python | test_checkpoint_state_dict | test_checkpoint_state_dict | 1,448 | 1,456 | 1,448 | 1,448 | f168e7c579cbb66dc4d93e134f4a52fc2babb57d | bigcode/the-stack | train |
35a96c1130ad6858ef5be54d | train | function | def test_model_checkpoint_simple_recovery_from_existing_non_empty(dirname):
def _test(ext, require_empty):
previous_fname = os.path.join(dirname, f"{_PREFIX}_obj_{1}{ext}")
with open(previous_fname, "w") as f:
f.write("test")
h = ModelCheckpoint(dirname, _PREFIX, create_dir=True... | def test_model_checkpoint_simple_recovery_from_existing_non_empty(dirname):
| def _test(ext, require_empty):
previous_fname = os.path.join(dirname, f"{_PREFIX}_obj_{1}{ext}")
with open(previous_fname, "w") as f:
f.write("test")
h = ModelCheckpoint(dirname, _PREFIX, create_dir=True, require_empty=require_empty)
engine = Engine(lambda e, b: None)
... | _save)
fname = h.last_checkpoint
assert isinstance(fname, str)
assert os.path.join(dirname, _PREFIX) in fname
assert os.path.exists(fname)
loaded_objects = torch.load(fname)
assert loaded_objects == model.state_dict()
def test_model_checkpoint_simple_recovery_from_existing_non_empty(dirname):
| 66 | 66 | 223 | 13 | 53 | OBITORASU/ignite | tests/ignite/handlers/test_checkpoint.py | Python | test_model_checkpoint_simple_recovery_from_existing_non_empty | test_model_checkpoint_simple_recovery_from_existing_non_empty | 537 | 562 | 537 | 537 | d6f8b8b5b997752637c59d02d285b5f0803a92d3 | bigcode/the-stack | train |
2a76786a3c99ccd749aca74a | train | function | def test_checkpoint_with_score_name_and_function():
def _test(to_save, obj, name):
save_handler = MagicMock(spec=BaseSaveHandler)
checkpointer = Checkpoint(
to_save, save_handler=save_handler, score_name="loss", score_function=lambda e: e.state.score
)
trainer = Engine(... | def test_checkpoint_with_score_name_and_function():
| def _test(to_save, obj, name):
save_handler = MagicMock(spec=BaseSaveHandler)
checkpointer = Checkpoint(
to_save, save_handler=save_handler, score_name="loss", score_function=lambda e: e.state.score
)
trainer = Engine(lambda e, b: None)
trainer.state = State(epo... | checkpointer.last_checkpoint == f"{name}_0.7800.pt"
model = DummyModel()
to_save = {"model": model}
_test(to_save, model.state_dict(), "model")
model = DummyModel()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
to_save = {"model": model, "optimizer": optimizer}
_test(to_save, {"... | 111 | 111 | 370 | 9 | 102 | OBITORASU/ignite | tests/ignite/handlers/test_checkpoint.py | Python | test_checkpoint_with_score_name_and_function | test_checkpoint_with_score_name_and_function | 276 | 312 | 276 | 276 | f3f66376f7e240d483a2d198370ddb41f972c0f2 | bigcode/the-stack | train |
1faa8fbafca792ccbc072b14 | train | function | def make_boilerplate(dest, app_name):
if not os.path.exists(dest):
print("Destination directory does not exist")
return
# app_name should be in snake_case
app_name = frappe.scrub(app_name)
hooks = frappe._dict()
hooks.app_name = app_name
app_title = hooks.app_name.replace("_", " ").title()
for key in ("App... | def make_boilerplate(dest, app_name):
| if not os.path.exists(dest):
print("Destination directory does not exist")
return
# app_name should be in snake_case
app_name = frappe.scrub(app_name)
hooks = frappe._dict()
hooks.app_name = app_name
app_title = hooks.app_name.replace("_", " ").title()
for key in ("App Title (default: {0})".format(app_titl... | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals, print_function
import frappe, os, re
from frappe.utils import touch_file, encode, cstr
def make_boilerplate(dest, app_name):
| 68 | 256 | 1,042 | 10 | 57 | vignesharumainayagam/engagex-frappe-backup- | frappe/utils/boilerplate.py | Python | make_boilerplate | make_boilerplate | 9 | 99 | 9 | 9 | bee2b5790c158e5a6f7c77be04d60ef94647dc00 | bigcode/the-stack | train |
3bb82e5cf2923feb51ee861b | train | function | def extension_file(module, canary):
if ENABLE_SUPPORT_DETECTION and not hasattr(GSSAPI_LIB, canary):
print('Skipping the %s extension because it '
'is not supported by your GSSAPI implementation...' % module)
return
try:
ENUM_EXTS.append(
make_extension('gssapi... | def extension_file(module, canary):
| if ENABLE_SUPPORT_DETECTION and not hasattr(GSSAPI_LIB, canary):
print('Skipping the %s extension because it '
'is not supported by your GSSAPI implementation...' % module)
return
try:
ENUM_EXTS.append(
make_extension('gssapi.raw._enum_extensions.ext_%s', modul... | =compile_args,
library_dirs=library_dirs,
libraries=libraries,
sources=[source],
**kwargs
)
# detect support
def main_file(module):
return make_extension('gssapi.raw.%s', module)
ENUM_EXTS = []
def extension_file(module, canary):
| 63 | 64 | 115 | 8 | 55 | steffen-kiess/python-gssapi | setup.py | Python | extension_file | extension_file | 289 | 303 | 289 | 289 | dcd52889e93b52831633cd07b2ab66317524b847 | bigcode/the-stack | train |
449934b201d2c6ad4647f09f | train | function | def get_output(*args, **kwargs):
res = subprocess.check_output(*args, shell=True, **kwargs)
decoded = res.decode('utf-8')
return decoded.strip()
| def get_output(*args, **kwargs):
| res = subprocess.check_output(*args, shell=True, **kwargs)
decoded = res.decode('utf-8')
return decoded.strip()
| cythonize
print("Building from Cython files...", file=sys.stderr)
SOURCE_EXT = 'pyx'
except ImportError:
print("Cython not found, building from C files...",
file=sys.stderr)
SOURCE_EXT = 'c'
def get_output(*args, **kwargs):
| 64 | 64 | 39 | 9 | 55 | steffen-kiess/python-gssapi | setup.py | Python | get_output | get_output | 33 | 36 | 33 | 33 | 714000910af28a3486482db64e1a82bb58e7d6c5 | bigcode/the-stack | train |
f80bcdff0ef7f974b5292f20 | train | class | class GSSAPIDistribution(Distribution, object):
def run_command(self, command):
self._last_run_command = command
Distribution.run_command(self, command)
@property
def ext_modules(self):
if SOURCE_EXT != 'pyx':
return getattr(self, '_ext_modules', None)
if getatt... | class GSSAPIDistribution(Distribution, object):
| def run_command(self, command):
self._last_run_command = command
Distribution.run_command(self, command)
@property
def ext_modules(self):
if SOURCE_EXT != 'pyx':
return getattr(self, '_ext_modules', None)
if getattr(self, '_ext_modules', None) is None:
... | :
with open(SKIP_CYTHON_FILE, 'w') as flag_file:
flag_file.write('COMPILE_FROM_C_ONLY')
sdist.run(self)
os.remove(SKIP_CYTHON_FILE)
DONT_CYTHONIZE_FOR = ('clean',)
class GSSAPIDistribution(Distribution, object):
| 69 | 69 | 231 | 12 | 57 | steffen-kiess/python-gssapi | setup.py | Python | GSSAPIDistribution | GSSAPIDistribution | 230 | 262 | 230 | 230 | 0cd7a8c464896517623e23c15789f610b80011c9 | bigcode/the-stack | train |
adf553743731bf3eabf50152 | train | function | def make_extension(name_fmt, module, **kwargs):
"""Helper method to remove the repetition in extension declarations."""
source = name_fmt.replace('.', '/') % module + '.' + SOURCE_EXT
if not os.path.exists(source):
raise OSError(source)
return Extension(
name_fmt % module,
extra_... | def make_extension(name_fmt, module, **kwargs):
| """Helper method to remove the repetition in extension declarations."""
source = name_fmt.replace('.', '/') % module + '.' + SOURCE_EXT
if not os.path.exists(source):
raise OSError(source)
return Extension(
name_fmt % module,
extra_link_args=link_args,
extra_compile_args=... | , mods):
self._cythonized_ext_modules = None
self._ext_modules = mods
@ext_modules.deleter
def ext_modules(self):
del self._ext_modules
del self._cythonized_ext_modules
def make_extension(name_fmt, module, **kwargs):
| 64 | 64 | 102 | 11 | 52 | steffen-kiess/python-gssapi | setup.py | Python | make_extension | make_extension | 265 | 278 | 265 | 265 | f3156d3223a7b3765462e086641bd7f23fd1ed98 | bigcode/the-stack | train |
f6e2523b05d40c2e7ad7ceb2 | train | function | def gssapi_modules(lst):
# filter out missing files
res = [mod for mod in lst if mod is not None]
# add in supported mech files
res.extend(
make_extension('gssapi.raw.mech_%s', mech)
for mech in os.environ.get('GSSAPI_MECHS', 'krb5').split(',')
)
# add in any present enum exten... | def gssapi_modules(lst):
# filter out missing files
| res = [mod for mod in lst if mod is not None]
# add in supported mech files
res.extend(
make_extension('gssapi.raw.mech_%s', mech)
for mech in os.environ.get('GSSAPI_MECHS', 'krb5').split(',')
)
# add in any present enum extension files
res.extend(ENUM_EXTS)
return res
| _extension('gssapi.raw._enum_extensions.ext_%s', module,
include_dirs=['gssapi/raw/'])
)
except OSError:
pass
return make_extension('gssapi.raw.ext_%s', module)
def gssapi_modules(lst):
# filter out missing files
| 64 | 64 | 102 | 14 | 50 | steffen-kiess/python-gssapi | setup.py | Python | gssapi_modules | gssapi_modules | 306 | 319 | 306 | 307 | a3411a548406bd149bf392b350d9808fa9c54b97 | bigcode/the-stack | train |
78c06b3c302b2fb4d5b41f83 | train | class | class sdist_gssapi(sdist):
def run(self):
if not self.dry_run:
with open(SKIP_CYTHON_FILE, 'w') as flag_file:
flag_file.write('COMPILE_FROM_C_ONLY')
sdist.run(self)
os.remove(SKIP_CYTHON_FILE)
| class sdist_gssapi(sdist):
| def run(self):
if not self.dry_run:
with open(SKIP_CYTHON_FILE, 'w') as flag_file:
flag_file.write('COMPILE_FROM_C_ONLY')
sdist.run(self)
os.remove(SKIP_CYTHON_FILE)
| "
"GSSAPI_SUPPORT_DETECT to 'false'")
GSSAPI_LIB = ctypes.CDLL(os.path.join(main_path, main_lib))
# add in the flag that causes us not to compile from Cython when
# installing from an sdist
class sdist_gssapi(sdist):
| 64 | 64 | 66 | 9 | 54 | steffen-kiess/python-gssapi | setup.py | Python | sdist_gssapi | sdist_gssapi | 216 | 224 | 216 | 216 | f4642492a6140476e189dcd227f5429974e7803c | bigcode/the-stack | train |
556aba9cd591a4a1d9eebd30 | train | function | def main_file(module):
return make_extension('gssapi.raw.%s', module)
| def main_file(module):
| return make_extension('gssapi.raw.%s', module)
| raise OSError(source)
return Extension(
name_fmt % module,
extra_link_args=link_args,
extra_compile_args=compile_args,
library_dirs=library_dirs,
libraries=libraries,
sources=[source],
**kwargs
)
# detect support
def main_file(module):
| 64 | 64 | 19 | 5 | 58 | steffen-kiess/python-gssapi | setup.py | Python | main_file | main_file | 282 | 283 | 282 | 282 | e960d115cc5fb0bb9d177f9c44f13f0a7d70516c | bigcode/the-stack | train |
e9a2e33bf233a8f77746a2e8 | train | class | class LayoutLMv2Config(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`LayoutLMv2Model`]. It is used
to instantiate an LayoutLMv2 model according to the specified arguments, defining the model architecture.
Instantiating a configuration with the defaults will yi... | class LayoutLMv2Config(PretrainedConfig):
| r"""
This is the configuration class to store the configuration of a [`LayoutLMv2Model`]. It is used
to instantiate an LayoutLMv2 model according to the specified arguments, defining the model architecture.
Instantiating a configuration with the defaults will yield a similar configuration to that of the... |
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing... | 256 | 256 | 2,336 | 11 | 244 | liminghao1630/transformers | src/transformers/models/layoutlmv2/configuration_layoutlmv2.py | Python | LayoutLMv2Config | LayoutLMv2Config | 35 | 224 | 35 | 35 | 95bc1acabcd0a4a0da0dec18f1196deaa2b76838 | bigcode/the-stack | train |
2a90137d8c1beaa34d4a645d | train | function | def classify_to_subfolder():
df = pd.read_csv("~/scratch-shared/ximeng/dataset_ximeng.csv",';')
for index, row in df.iterrows():
if row['type'] == 'compound':
if os.path.exists(cwd + str(index) + '.tif'):
shutil.move(cwd + str(index) + '.tif', cwd + 'compound')
elif r... | def classify_to_subfolder():
| df = pd.read_csv("~/scratch-shared/ximeng/dataset_ximeng.csv",';')
for index, row in df.iterrows():
if row['type'] == 'compound':
if os.path.exists(cwd + str(index) + '.tif'):
shutil.move(cwd + str(index) + '.tif', cwd + 'compound')
elif row['type'] == 'control':
... | -images-pvc/ximeng/five_channel_images/'
#classify_to_subfolder()
#write_tfrecords()
parsed_image_dataset = read_tfrecord_file()
final_model = build_model(parsed_image_dataset)
model_probability(final_model,parsed_image_dataset)
def classify_to_subfolder():
| 64 | 64 | 128 | 6 | 58 | pharmbio/ximeng_project | Old_Scripts/build_resnet50_five_channels.py | Python | classify_to_subfolder | classify_to_subfolder | 21 | 29 | 21 | 21 | 6a9b60dbd6cdbe1a5f94915c5fb96dff1d949d55 | bigcode/the-stack | train |
f35520f6a498544daf72e7ee | train | function | def build_model(parsed_image_dataset):
input_layer = tf.keras.layers.Input(shape=(2160,2160,5))
second_layer = layers.Conv2D(3, 3, 9, activation='relu')(input_layer)
resnet50_layers = tf.keras.applications.ResNet50(include_top=True, weights='imagenet')(second_layer)
outputs = tf.keras.layers.Dense(... | def build_model(parsed_image_dataset):
| input_layer = tf.keras.layers.Input(shape=(2160,2160,5))
second_layer = layers.Conv2D(3, 3, 9, activation='relu')(input_layer)
resnet50_layers = tf.keras.applications.ResNet50(include_top=True, weights='imagenet')(second_layer)
outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(resnet50_layers... | label': tf.io.FixedLenFeature([], tf.int64),
# 'image_raw': tf.io.FixedLenFeature([], tf.string),}
# parsed_image_dataset =tf.io.parse_single_example(raw_dataset.map, image_feature_description)
# return parsed_image_dataset
def build_model(parsed_image_dataset):
| 64 | 64 | 192 | 8 | 55 | pharmbio/ximeng_project | Old_Scripts/build_resnet50_five_channels.py | Python | build_model | build_model | 74 | 91 | 74 | 75 | 81db8ff4684305a144e210b8bf67107e3d614cd5 | bigcode/the-stack | train |
92e54b410597ac3668022602 | train | function | def read_tfrecord_file():
raw_dataset = tf.keras.preprocessing.image_dataset_from_directory('/home/jovyan/mnt/external-images-pvc/ximeng/five_channel_images/', labels='inferred', label_mode='int')
#raw_dataset = tf.data.TFRecordDataset("/home/jovyan/mnt/external-images-pvc/ximeng/train_five_channels.tfrecords")... | def read_tfrecord_file():
| raw_dataset = tf.keras.preprocessing.image_dataset_from_directory('/home/jovyan/mnt/external-images-pvc/ximeng/five_channel_images/', labels='inferred', label_mode='int')
#raw_dataset = tf.data.TFRecordDataset("/home/jovyan/mnt/external-images-pvc/ximeng/train_five_channels.tfrecords")
parsed_image_dataset ... | ()
def _parse_function(example_proto):
image_feature_description = {
'label': tf.io.FixedLenFeature([], tf.int64),
'image_raw': tf.io.FixedLenFeature([], tf.string),}
return tf.io.parse_single_example(example_proto, image_feature_description)
def read_tfrecord_file():
| 64 | 64 | 101 | 7 | 57 | pharmbio/ximeng_project | Old_Scripts/build_resnet50_five_channels.py | Python | read_tfrecord_file | read_tfrecord_file | 55 | 59 | 55 | 55 | caa9c048924d5a94104fbf2a6b5205393fd94af1 | bigcode/the-stack | train |
eb48d7bdcae1458c4adc9ae2 | train | function | def model_probability(model, dataset):
probability_model = tf.keras.Sequential([model,
tf.keras.layers.Softmax()])
predictions = probability_model.predict(dataset)
predictions[10]
| def model_probability(model, dataset):
| probability_model = tf.keras.Sequential([model,
tf.keras.layers.Softmax()])
predictions = probability_model.predict(dataset)
predictions[10]
| =['accuracy'])
model.summary()
model.fit(parsed_image_dataset, epochs=10)
callbacks = [
tf.keras.callbacks.EarlyStopping(patience=2, monitor='val_loss'),
tf.keras.callbacks.TensorBoard(log_dir='./logs')
]
return model
def model_probability(model, dataset):
| 64 | 64 | 40 | 7 | 56 | pharmbio/ximeng_project | Old_Scripts/build_resnet50_five_channels.py | Python | model_probability | model_probability | 92 | 97 | 92 | 92 | d59e8fce015bad269d8b4096d99399bb664215ae | bigcode/the-stack | train |
f4de182060694799dd7de13a | train | function | def main():
global cwd
cwd='/home/jovyan/mnt/external-images-pvc/ximeng/five_channel_images/'
#classify_to_subfolder()
#write_tfrecords()
parsed_image_dataset = read_tfrecord_file()
final_model = build_model(parsed_image_dataset)
model_probability(final_model,parsed_image_dataset)
| def main():
| global cwd
cwd='/home/jovyan/mnt/external-images-pvc/ximeng/five_channel_images/'
#classify_to_subfolder()
#write_tfrecords()
parsed_image_dataset = read_tfrecord_file()
final_model = build_model(parsed_image_dataset)
model_probability(final_model,parsed_image_dataset)
| import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from PIL import Image
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
import shutil
def main():
| 46 | 64 | 76 | 3 | 42 | pharmbio/ximeng_project | Old_Scripts/build_resnet50_five_channels.py | Python | main | main | 11 | 18 | 11 | 11 | 8ecd6d3c53b958049d1bd6f428d679076726ece5 | bigcode/the-stack | train |
483bdcd5f2d0e0a5a8733959 | train | function | def write_tfrecords():
classes={'control','compound'}
writer = tf.compat.v1.python_io.TFRecordWriter("/home/jovyan/mnt/external-images-pvc/ximeng/train_five_channels.tfrecords")
for index,name in enumerate(classes):
class_path=cwd+name+'/'
for image_name in os.listdir(class_path):
... | def write_tfrecords():
| classes={'control','compound'}
writer = tf.compat.v1.python_io.TFRecordWriter("/home/jovyan/mnt/external-images-pvc/ximeng/train_five_channels.tfrecords")
for index,name in enumerate(classes):
class_path=cwd+name+'/'
for image_name in os.listdir(class_path):
if image_name.endswi... | (index) + '.tif', cwd + 'compound')
elif row['type'] == 'control':
if os.path.exists(cwd + str(index) + '.tif'):
shutil.move(cwd + str(index) + '.tif', cwd + 'control')
def write_tfrecords():
| 64 | 64 | 187 | 7 | 57 | pharmbio/ximeng_project | Old_Scripts/build_resnet50_five_channels.py | Python | write_tfrecords | write_tfrecords | 32 | 47 | 32 | 32 | 4d7a6a26cc4eeed0e0347bcaec40b5f23782f33a | bigcode/the-stack | train |
32668545d59d2156b8cfcb5a | train | function | def _parse_function(example_proto):
image_feature_description = {
'label': tf.io.FixedLenFeature([], tf.int64),
'image_raw': tf.io.FixedLenFeature([], tf.string),}
return tf.io.parse_single_example(example_proto, image_feature_description)
| def _parse_function(example_proto):
| image_feature_description = {
'label': tf.io.FixedLenFeature([], tf.int64),
'image_raw': tf.io.FixedLenFeature([], tf.string),}
return tf.io.parse_single_example(example_proto, image_feature_description)
| (feature={
"label": tf.train.Feature(int64_list=tf.train.Int64List(value=[index])),
'image_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[image_raw]))
}))
writer.write(working_image.SerializeToString())
writer.close()
def _parse_fu... | 64 | 64 | 56 | 7 | 57 | pharmbio/ximeng_project | Old_Scripts/build_resnet50_five_channels.py | Python | _parse_function | _parse_function | 49 | 53 | 49 | 49 | 1464c132db4c5d8f9757d116965e420486ea1ccb | bigcode/the-stack | train |
c08f541540b8c576f39a24ce | train | function | @login_required
def mmt_home(request):
return render(request, 'mmt/mmt_home.html')
| @login_required
def mmt_home(request):
| return render(request, 'mmt/mmt_home.html')
| from django.shortcuts import render
from django.contrib.auth.decorators import login_required
@login_required
def mmt_home(request):
| 24 | 64 | 22 | 9 | 14 | lauriefacer/Facer | mmt/views.py | Python | mmt_home | mmt_home | 5 | 7 | 5 | 6 | 27957fd379964a2d23377ad675438684107127a2 | bigcode/the-stack | train |
aa5ed3d337133a7db517fac6 | train | class | class DictItem(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
... | class DictItem(object):
| """NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): Th... | # coding: utf-8
"""
Influx OSS API Service.
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
OpenAPI spec version: 2.0.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class DictItem(object):... | 84 | 256 | 874 | 5 | 78 | wasted925/influxdb-client-python | influxdb_client/domain/dict_item.py | Python | DictItem | DictItem | 19 | 159 | 19 | 19 | 59a9268d6b3c2a3517719baa5961015be5d5a886 | bigcode/the-stack | train |
e8174d2e11a5b78cdec57130 | train | function | def test_exception_value_error():
new_exception = exception.ValueError('error')
try:
raise new_exception
except exception.ValueError:
pass
| def test_exception_value_error():
| new_exception = exception.ValueError('error')
try:
raise new_exception
except exception.ValueError:
pass
| _exception = exception.SizeError('error')
try:
raise new_exception
except exception.SizeError:
pass
def test_exception_type_error():
new_exception = exception.TypeError('error')
try:
raise new_exception
except exception.TypeError:
pass
def test_exception_value_err... | 64 | 64 | 33 | 6 | 57 | anukaal/opytimizer | tests/opytimizer/utils/test_exception.py | Python | test_exception_value_error | test_exception_value_error | 49 | 55 | 49 | 49 | 33bca6d61a2aa59bc0856aefb247aeae1ddf333d | bigcode/the-stack | train |
e37fbca83e33e7bf060132d9 | train | function | def test_exception_build_error():
new_exception = exception.BuildError('error')
try:
raise new_exception
except exception.BuildError:
pass
| def test_exception_build_error():
| new_exception = exception.BuildError('error')
try:
raise new_exception
except exception.BuildError:
pass
| = exception.Error('Error', 'error')
try:
raise new_exception
except exception.Error:
pass
def test_exception_argument_error():
new_exception = exception.ArgumentError('error')
try:
raise new_exception
except exception.ArgumentError:
pass
def test_exception_build_... | 64 | 64 | 33 | 6 | 57 | anukaal/opytimizer | tests/opytimizer/utils/test_exception.py | Python | test_exception_build_error | test_exception_build_error | 22 | 28 | 22 | 22 | d60e946a2d9caee37012eeb2a7ffe78cec7e6c4b | bigcode/the-stack | train |
664f6caa2e0bcd192911996b | train | function | def test_exception_type_error():
new_exception = exception.TypeError('error')
try:
raise new_exception
except exception.TypeError:
pass
| def test_exception_type_error():
| new_exception = exception.TypeError('error')
try:
raise new_exception
except exception.TypeError:
pass
| _exception = exception.BuildError('error')
try:
raise new_exception
except exception.BuildError:
pass
def test_exception_size_error():
new_exception = exception.SizeError('error')
try:
raise new_exception
except exception.SizeError:
pass
def test_exception_type_er... | 64 | 64 | 33 | 6 | 57 | anukaal/opytimizer | tests/opytimizer/utils/test_exception.py | Python | test_exception_type_error | test_exception_type_error | 40 | 46 | 40 | 40 | d7ea640bdea97bd2ccf3c7fc9b8f5673d72bda7c | bigcode/the-stack | train |
ed1ba95521e218dbc1049d73 | train | function | def test_exception_error():
new_exception = exception.Error('Error', 'error')
try:
raise new_exception
except exception.Error:
pass
| def test_exception_error():
| new_exception = exception.Error('Error', 'error')
try:
raise new_exception
except exception.Error:
pass
| from opytimizer.utils import exception
def test_exception_error():
| 14 | 64 | 33 | 5 | 8 | anukaal/opytimizer | tests/opytimizer/utils/test_exception.py | Python | test_exception_error | test_exception_error | 4 | 10 | 4 | 4 | 8a074280376e8e0d6591b8c874442799a05ce3e4 | bigcode/the-stack | train |
fb4d1d2659e3063ffaa811e2 | train | function | def test_exception_argument_error():
new_exception = exception.ArgumentError('error')
try:
raise new_exception
except exception.ArgumentError:
pass
| def test_exception_argument_error():
| new_exception = exception.ArgumentError('error')
try:
raise new_exception
except exception.ArgumentError:
pass
| from opytimizer.utils import exception
def test_exception_error():
new_exception = exception.Error('Error', 'error')
try:
raise new_exception
except exception.Error:
pass
def test_exception_argument_error():
| 48 | 64 | 33 | 6 | 41 | anukaal/opytimizer | tests/opytimizer/utils/test_exception.py | Python | test_exception_argument_error | test_exception_argument_error | 13 | 19 | 13 | 13 | 45119816af44c4bc0ec0dbc9a90ba634346132d6 | bigcode/the-stack | train |
4bb5eeff4e82069ea80b62e9 | train | function | def test_exception_size_error():
new_exception = exception.SizeError('error')
try:
raise new_exception
except exception.SizeError:
pass
| def test_exception_size_error():
| new_exception = exception.SizeError('error')
try:
raise new_exception
except exception.SizeError:
pass
| _exception = exception.ArgumentError('error')
try:
raise new_exception
except exception.ArgumentError:
pass
def test_exception_build_error():
new_exception = exception.BuildError('error')
try:
raise new_exception
except exception.BuildError:
pass
def test_exceptio... | 64 | 64 | 33 | 6 | 57 | anukaal/opytimizer | tests/opytimizer/utils/test_exception.py | Python | test_exception_size_error | test_exception_size_error | 31 | 37 | 31 | 31 | 13f8ac4253ff90d6abb2d4cb5f0245116d7e40c6 | bigcode/the-stack | train |
85161431de58d68a9b612153 | train | function | def demo():
import os
from vizer.draw import draw_boxes
yolo = YOLOv3("cfg/yolo_v3.cfg", "weight/yolov3.weights", "cfg/coco.names")
print("yolo.size =", yolo.size)
root = "./demo"
resdir = os.path.join(root, "results")
os.makedirs(resdir, exist_ok=True)
files = [os.path.join(root, file)... | def demo():
| import os
from vizer.draw import draw_boxes
yolo = YOLOv3("cfg/yolo_v3.cfg", "weight/yolov3.weights", "cfg/coco.names")
print("yolo.size =", yolo.size)
root = "./demo"
resdir = os.path.join(root, "results")
os.makedirs(resdir, exist_ok=True)
files = [os.path.join(root, file) for file in... | ].long()
return bbox.numpy(), cls_conf.numpy(), cls_ids.numpy()
def load_class_names(self, namesfile):
with open(namesfile, 'r', encoding='utf8') as fp:
class_names = [line.strip() for line in fp.readlines()]
return class_names
def demo():
| 65 | 65 | 218 | 3 | 61 | ge68pak/yolo_deepsort_pytorch | detector/YOLOv3/detector.py | Python | demo | demo | 76 | 95 | 76 | 76 | af5ff0415bdbbe7491fd2a2e2d70920696554a18 | bigcode/the-stack | train |
000746781a1184642f3f4d3b | train | class | class YOLOv3(object):
def __init__(self, cfgfile, weightfile, namesfile, score_thresh=0.7, conf_thresh=0.01, nms_thresh=0.45,
is_xywh=False, use_cuda=True):
# net definition
self.net = Darknet(cfgfile)
self.net.load_weights(weightfile)
logger = logging.getLogger("roo... | class YOLOv3(object):
| def __init__(self, cfgfile, weightfile, namesfile, score_thresh=0.7, conf_thresh=0.01, nms_thresh=0.45,
is_xywh=False, use_cuda=True):
# net definition
self.net = Darknet(cfgfile)
self.net.load_weights(weightfile)
logger = logging.getLogger("root.detector")
l... | import torch
import logging
import numpy as np
import cv2
from darknet import Darknet
from yolo_utils import get_all_boxes, nms, post_process, xywh_to_xyxy, xyxy_to_xywh
from nms import boxes_nms
class YOLOv3(object):
| 63 | 198 | 661 | 7 | 55 | ge68pak/yolo_deepsort_pytorch | detector/YOLOv3/detector.py | Python | YOLOv3 | YOLOv3 | 11 | 73 | 11 | 11 | 04207c26a5a80b1ef1f41cf0cc31cd73bed7fb1d | bigcode/the-stack | train |
fec87cff83f844de93148490 | train | class | class StockInstitutionalInvestorHolder(StockActorBase, TradableMeetActor):
"""
市场参与者:股票的机构投资者
"""
__tablename__ = 'stock_institutional_investor_holder'
report_period = Column(String(length=32))
report_date = Column(DateTime)
# 持股数
holding_numbers = Column(Float)
# 持股比例
holding_... | class StockInstitutionalInvestorHolder(StockActorBase, TradableMeetActor):
| """
市场参与者:股票的机构投资者
"""
__tablename__ = 'stock_institutional_investor_holder'
report_period = Column(String(length=32))
report_date = Column(DateTime)
# 持股数
holding_numbers = Column(Float)
# 持股比例
holding_ratio = Column(Float)
# 持股市值
holding_values = Column(Float)
| = Column(DateTime)
# 持股数
holding_numbers = Column(Float)
# 持股比例
holding_ratio = Column(Float)
# 持股市值
holding_values = Column(Float)
class StockInstitutionalInvestorHolder(StockActorBase, TradableMeetActor):
| 64 | 64 | 108 | 16 | 48 | aaron8tang/zvt | zvt/domain/actor/stock_actor.py | Python | StockInstitutionalInvestorHolder | StockInstitutionalInvestorHolder | 45 | 59 | 45 | 45 | 77703d41e0f9baeb697868d3471d66e218d3cf62 | bigcode/the-stack | train |
c817fe6782ee6c639f76f7ad | train | class | class StockTopTenFreeHolder(StockActorBase, TradableMeetActor):
"""
市场参与者:股票的前十大流通股东
"""
__tablename__ = 'stock_top_ten_free_holder'
report_period = Column(String(length=32))
report_date = Column(DateTime)
# 持股数
holding_numbers = Column(Float)
# 持股比例
holding_ratio = Column(Floa... | class StockTopTenFreeHolder(StockActorBase, TradableMeetActor):
| """
市场参与者:股票的前十大流通股东
"""
__tablename__ = 'stock_top_ten_free_holder'
report_period = Column(String(length=32))
report_date = Column(DateTime)
# 持股数
holding_numbers = Column(Float)
# 持股比例
holding_ratio = Column(Float)
# 持股市值
holding_values = Column(Float)
| , String, DateTime, Float, Boolean, Integer
from sqlalchemy.orm import declarative_base
from zvt.contract.register import register_schema
from zvt.contract.schema import TradableMeetActor
StockActorBase = declarative_base()
class StockTopTenFreeHolder(StockActorBase, TradableMeetActor):
| 64 | 64 | 109 | 16 | 48 | aaron8tang/zvt | zvt/domain/actor/stock_actor.py | Python | StockTopTenFreeHolder | StockTopTenFreeHolder | 11 | 25 | 11 | 11 | e291774fafe051439bafe5f228ba148c7eb01829 | bigcode/the-stack | train |
26dfe7dafa2aa5633d15eb5c | train | class | class StockActorSummary(StockActorBase, TradableMeetActor):
__tablename__ = 'stock_actor_summary'
# tradable code
code = Column(String(length=64))
# tradable name
name = Column(String(length=128))
report_period = Column(String(length=32))
report_date = Column(DateTime)
# 变动比例
chang... | class StockActorSummary(StockActorBase, TradableMeetActor):
| __tablename__ = 'stock_actor_summary'
# tradable code
code = Column(String(length=64))
# tradable name
name = Column(String(length=128))
report_period = Column(String(length=32))
report_date = Column(DateTime)
# 变动比例
change_ratio = Column(Float)
# 是否完成
is_complete = Column(... | report_date = Column(DateTime)
# 持股数
holding_numbers = Column(Float)
# 持股比例
holding_ratio = Column(Float)
# 持股市值
holding_values = Column(Float)
class StockActorSummary(StockActorBase, TradableMeetActor):
| 64 | 64 | 163 | 14 | 50 | aaron8tang/zvt | zvt/domain/actor/stock_actor.py | Python | StockActorSummary | StockActorSummary | 62 | 85 | 62 | 62 | 04492ee1260d2b0419c2d0650616b48bd85aa5bd | bigcode/the-stack | train |
ffe87f9f1f9dd370c0367da6 | train | class | class StockTopTenHolder(StockActorBase, TradableMeetActor):
"""
市场参与者:股票的前十大股东
"""
__tablename__ = 'stock_top_ten_holder'
report_period = Column(String(length=32))
report_date = Column(DateTime)
# 持股数
holding_numbers = Column(Float)
# 持股比例
holding_ratio = Column(Float)
# 持股... | class StockTopTenHolder(StockActorBase, TradableMeetActor):
| """
市场参与者:股票的前十大股东
"""
__tablename__ = 'stock_top_ten_holder'
report_period = Column(String(length=32))
report_date = Column(DateTime)
# 持股数
holding_numbers = Column(Float)
# 持股比例
holding_ratio = Column(Float)
# 持股市值
holding_values = Column(Float)
| _date = Column(DateTime)
# 持股数
holding_numbers = Column(Float)
# 持股比例
holding_ratio = Column(Float)
# 持股市值
holding_values = Column(Float)
class StockTopTenHolder(StockActorBase, TradableMeetActor):
| 64 | 64 | 105 | 15 | 49 | aaron8tang/zvt | zvt/domain/actor/stock_actor.py | Python | StockTopTenHolder | StockTopTenHolder | 28 | 42 | 28 | 28 | e7b4c8a3f92c8b26a977001dcacbdffd99b19a6b | bigcode/the-stack | train |
2eb4fc75e8757f315c28edbe | train | class | class Cfg2(object):
"""Class: Cfg2
Description: Class stub holder for Cfg class with new attributes.
Methods:
__init__
"""
def __init__(self, repset_hosts=None):
"""Function: __init__
Description: Class initialization.
Arguments:
"""
self... | class Cfg2(object):
| """Class: Cfg2
Description: Class stub holder for Cfg class with new attributes.
Methods:
__init__
"""
def __init__(self, repset_hosts=None):
"""Function: __init__
Description: Class initialization.
Arguments:
"""
self.name = "name"
... | "host"
self.port = 27017
self.auth = True
self.repset = "repset_name"
self.conf_file = "conf_file"
self.repset_hosts = repset_hosts
self.db_auth = "db_name"
class Cfg2(object):
| 64 | 64 | 212 | 6 | 58 | mjpernot/mongo-lib | test/unit/mongo_libs/crt_coll_inst.py | Python | Cfg2 | Cfg2 | 70 | 106 | 70 | 71 | 34bcc059bb72d7e2a13b2f39481a7361c1183aed | bigcode/the-stack | train |
fe16239f24b65895933f9fe2 | train | class | class Cfg3(object):
"""Class: Cfg3
Description: Class stub holder for Cfg class with new attributes.
Methods:
__init__
"""
def __init__(self, repset_hosts=None):
"""Function: __init__
Description: Class initialization.
Arguments:
"""
self... | class Cfg3(object):
| """Class: Cfg3
Description: Class stub holder for Cfg class with new attributes.
Methods:
__init__
"""
def __init__(self, repset_hosts=None):
"""Function: __init__
Description: Class initialization.
Arguments:
"""
self.name = "name"
... | = "db_name"
self.auth_db = "mydatabase"
self.auth_mech = "SCRAM-SHA-1"
self.ssl_client_ca = None
self.ssl_client_cert = None
self.ssl_client_key = None
self.ssl_client_phrase = None
class Cfg3(object):
| 66 | 66 | 220 | 6 | 59 | mjpernot/mongo-lib | test/unit/mongo_libs/crt_coll_inst.py | Python | Cfg3 | Cfg3 | 109 | 145 | 109 | 110 | 60ddc380a5c6a6debc64ecc49b2ca3bd396a3d70 | bigcode/the-stack | train |
38631340567cee5560ad5e3c | train | class | class UnitTest(unittest.TestCase):
"""Class: UnitTest
Description: Class which is a representation of a unit testing.
Methods:
setUp
test_coll_set_ssl
test_rep_set_ssl
test_coll_none_ssl
test_rep_none_ssl
test_coll_no_ssl
test_rep_no_ssl
t... | class UnitTest(unittest.TestCase):
| """Class: UnitTest
Description: Class which is a representation of a unit testing.
Methods:
setUp
test_coll_set_ssl
test_rep_set_ssl
test_coll_none_ssl
test_rep_none_ssl
test_coll_no_ssl
test_rep_no_ssl
test_coll_mech_auth
test_coll... | _client_ca = None
self.ssl_client_cert = None
self.ssl_client_key = None
self.ssl_client_phrase = None
class Cfg3(object):
"""Class: Cfg3
Description: Class stub holder for Cfg class with new attributes.
Methods:
__init__
"""
def __init__(self, repset_hosts=N... | 256 | 256 | 1,586 | 7 | 249 | mjpernot/mongo-lib | test/unit/mongo_libs/crt_coll_inst.py | Python | UnitTest | UnitTest | 148 | 435 | 148 | 149 | a17a5830763d19c8ca6776bd75f9c1404b819bd0 | bigcode/the-stack | train |
eb8ff87d3d390a7465967c83 | train | class | class Cfg(object):
"""Class: Cfg
Description: Class stub holder for Cfg class.
Methods:
__init__
"""
def __init__(self, repset_hosts=None):
"""Function: __init__
Description: Class initialization.
Arguments:
"""
self.name = "name"
... | class Cfg(object):
| """Class: Cfg
Description: Class stub holder for Cfg class.
Methods:
__init__
"""
def __init__(self, repset_hosts=None):
"""Function: __init__
Description: Class initialization.
Arguments:
"""
self.name = "name"
self.user = "user"
... | os
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
# Third-party
import mock
# Local
sys.path.append(os.getcwd())
import mongo_libs
import version
__version__ = version.__version__
class Cfg(object):
| 63 | 64 | 152 | 5 | 58 | mjpernot/mongo-lib | test/unit/mongo_libs/crt_coll_inst.py | Python | Cfg | Cfg | 37 | 67 | 37 | 38 | b18b897f22c464d3a8c20324adf68facfe1973b4 | bigcode/the-stack | train |
fbe9c9754e1c3b7f589755d3 | train | function | def get_fd_or_server(config):
'''Tries to create the lockfile, using O_EXCL to
prevent races. If it succeeds it returns the FD.
Otherwise try and connect to the server specified in the lockfile.
If this succeeds, the server is returned. Otherwise remove the
lockfile and try again.'''
lockfile ... | def get_fd_or_server(config):
| '''Tries to create the lockfile, using O_EXCL to
prevent races. If it succeeds it returns the FD.
Otherwise try and connect to the server specified in the lockfile.
If this succeeds, the server is returned. Otherwise remove the
lockfile and try again.'''
lockfile = get_lockfile(config)
whi... | Storage
from .commands import known_commands, Commands
from .simple_config import SimpleConfig
from .exchange_rate import FxThread
def get_lockfile(config):
return os.path.join(config.path, 'daemon')
def remove_lockfile(lockfile):
os.unlink(lockfile)
def get_fd_or_server(config):
| 64 | 64 | 159 | 7 | 57 | Starry9/electrum | lib/daemon.py | Python | get_fd_or_server | get_fd_or_server | 52 | 68 | 52 | 52 | c4544317fcb55d9030c490c2a2ce9507efb4bf3e | bigcode/the-stack | train |
efef9abe7cad252f1217b2e2 | train | function | def remove_lockfile(lockfile):
os.unlink(lockfile)
| def remove_lockfile(lockfile):
| os.unlink(lockfile)
| _error
from .wallet import Wallet
from .storage import WalletStorage
from .commands import known_commands, Commands
from .simple_config import SimpleConfig
from .exchange_rate import FxThread
def get_lockfile(config):
return os.path.join(config.path, 'daemon')
def remove_lockfile(lockfile):
| 64 | 64 | 13 | 7 | 57 | Starry9/electrum | lib/daemon.py | Python | remove_lockfile | remove_lockfile | 48 | 49 | 48 | 48 | 956f42754bcf750ed19fa3fdd4581c4163627d9b | bigcode/the-stack | train |
7b6e1641696b98aac3a4d92e | train | function | def get_server(config):
lockfile = get_lockfile(config)
while True:
create_time = None
try:
with open(lockfile) as f:
(host, port), create_time = ast.literal_eval(f.read())
server = jsonrpclib.Server('http://%s:%d' % (host, port))
# Test da... | def get_server(config):
| lockfile = get_lockfile(config)
while True:
create_time = None
try:
with open(lockfile) as f:
(host, port), create_time = ast.literal_eval(f.read())
server = jsonrpclib.Server('http://%s:%d' % (host, port))
# Test daemon is running
... | os.O_EXCL | os.O_WRONLY), None
except OSError:
pass
server = get_server(config)
if server is not None:
return None, server
# Couldn't connect; remove lockfile and try again.
remove_lockfile(lockfile)
def get_server(config):
| 64 | 64 | 150 | 5 | 59 | Starry9/electrum | lib/daemon.py | Python | get_server | get_server | 71 | 87 | 71 | 71 | c6b578b380751a56d8c74ef34d7bdd0cc4d52744 | bigcode/the-stack | train |
bedaa127ec1055ccd6c7a0c0 | train | class | class Daemon(DaemonThread):
def __init__(self, config, fd):
DaemonThread.__init__(self)
self.config = config
if config.get('offline'):
self.network = None
self.fx = None
else:
self.network = Network(config)
self.network.start()
... | class Daemon(DaemonThread):
| def __init__(self, config, fd):
DaemonThread.__init__(self)
self.config = config
if config.get('offline'):
self.network = None
self.fx = None
else:
self.network = Network(config)
self.network.start()
self.fx = FxThread(confi... | # Couldn't connect; remove lockfile and try again.
remove_lockfile(lockfile)
def get_server(config):
lockfile = get_lockfile(config)
while True:
create_time = None
try:
with open(lockfile) as f:
(host, port), create_time = ast.literal_eval(f.read())
... | 256 | 256 | 1,430 | 8 | 248 | Starry9/electrum | lib/daemon.py | Python | Daemon | Daemon | 103 | 284 | 103 | 104 | 97755a410f323173bd39a9387ea765e306c4caf1 | bigcode/the-stack | train |
615cd2137765f6d815a6ae93 | train | class | class RequestHandler(SimpleJSONRPCRequestHandler):
def do_OPTIONS(self):
self.send_response(200)
self.end_headers()
def end_headers(self):
self.send_header("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept")
self.sen... | class RequestHandler(SimpleJSONRPCRequestHandler):
| def do_OPTIONS(self):
self.send_response(200)
self.end_headers()
def end_headers(self):
self.send_header("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept")
self.send_header("Access-Control-Allow-Origin", "*")
... | print_error("[get_server]", e)
if not create_time or create_time < time.time() - 1.0:
return None
# Sleep a bit and try again; it might have just been started
time.sleep(1.0)
class RequestHandler(SimpleJSONRPCRequestHandler):
| 64 | 64 | 79 | 9 | 55 | Starry9/electrum | lib/daemon.py | Python | RequestHandler | RequestHandler | 90 | 100 | 90 | 91 | e57c99602c50427eb0af2068548992cc87c2e496 | bigcode/the-stack | train |
ab5c5927ae3b660e49789b19 | train | function | def get_lockfile(config):
return os.path.join(config.path, 'daemon')
| def get_lockfile(config):
| return os.path.join(config.path, 'daemon')
| Network
from .util import json_decode, DaemonThread
from .util import print_error
from .wallet import Wallet
from .storage import WalletStorage
from .commands import known_commands, Commands
from .simple_config import SimpleConfig
from .exchange_rate import FxThread
def get_lockfile(config):
| 64 | 64 | 17 | 6 | 57 | Starry9/electrum | lib/daemon.py | Python | get_lockfile | get_lockfile | 44 | 45 | 44 | 44 | 94f3762e5cbd2eebfd98de312c567aec395e6acf | bigcode/the-stack | train |
00ce2dc778e9f5906fe84201 | train | function | @pytest.mark.noparallel(reason='Asynchronos behavior when loading locks')
def test_detach_dataset_lock_removal_shared_file(did_client, did_factory, root_account, rse_factory, vo):
rse, rse_id = rse_factory.make_posix_rse()
file = did_factory.upload_test_file(rse)
dataset_internal = did_factory.make_dataset(... | @pytest.mark.noparallel(reason='Asynchronos behavior when loading locks')
def test_detach_dataset_lock_removal_shared_file(did_client, did_factory, root_account, rse_factory, vo):
| rse, rse_id = rse_factory.make_posix_rse()
file = did_factory.upload_test_file(rse)
dataset_internal = did_factory.make_dataset()
dataset_internal_2 = did_factory.make_dataset()
container_internal = did_factory.make_container()
# make all scopes external
file, dataset, dataset_2, container ... | )
# Detach dataset from container, this should delete all locks on the dataset
did_client.detach_dids(**container, dids=[dataset_internal])
re_evaluator(once=True, did_limit=None)
dataset_locks = list(get_dataset_locks(**dataset_internal))
print("Dataset locks after detach: {0}".format(dataset_lo... | 142 | 142 | 475 | 42 | 100 | rucio/rucio | lib/rucio/tests/test_rule.py | Python | test_detach_dataset_lock_removal_shared_file | test_detach_dataset_lock_removal_shared_file | 1,470 | 1,502 | 1,470 | 1,471 | 14183a97c67c668ab0bf48afc4c8936da7479ca1 | bigcode/the-stack | train |
6232e0b183f47e61eccb30aa | train | function | @pytest.mark.noparallel(reason='Asynchronos behavior when loading locks')
def test_detach_dataset_lock_removal_shared_dataset(did_client, did_factory, root_account, rse_factory, vo):
rse, rse_id = rse_factory.make_posix_rse()
file = did_factory.upload_test_file(rse)
dataset_internal = did_factory.make_datas... | @pytest.mark.noparallel(reason='Asynchronos behavior when loading locks')
def test_detach_dataset_lock_removal_shared_dataset(did_client, did_factory, root_account, rse_factory, vo):
| rse, rse_id = rse_factory.make_posix_rse()
file = did_factory.upload_test_file(rse)
dataset_internal = did_factory.make_dataset()
container_internal = did_factory.make_container()
container_internal_2 = did_factory.make_container()
# make all scopes external
file, dataset, container, contai... | 2)
# Detach dataset from container, this should delete all locks on the dataset
did_client.detach_dids(**container, dids=[dataset_internal])
re_evaluator(once=True, did_limit=None)
dataset_locks = list(get_dataset_locks(**dataset_internal))
print("Dataset locks after detach: {0}".format(dataset_l... | 143 | 143 | 477 | 42 | 101 | rucio/rucio | lib/rucio/tests/test_rule.py | Python | test_detach_dataset_lock_removal_shared_dataset | test_detach_dataset_lock_removal_shared_dataset | 1,435 | 1,467 | 1,435 | 1,436 | 87c562ae5d57212291b2508ba0fbfc9dbecdcf0d | bigcode/the-stack | train |
1241e1ee8aebb2e16ef12037 | train | class | @pytest.mark.noparallel(reason='empties database tables, sets account limits, adds global rse attributes')
class TestReplicationRuleCore(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.db_session = session.get_session()
if config_get_bool('common', 'multi_vo', raise_exception=False, ... | @pytest.mark.noparallel(reason='empties database tables, sets account limits, adds global rse attributes')
class TestReplicationRuleCore(unittest.TestCase):
@classmethod
| def setUpClass(cls):
cls.db_session = session.get_session()
if config_get_bool('common', 'multi_vo', raise_exception=False, default=False):
cls.vo = {'vo': get_vo()}
else:
cls.vo = {}
# Add test RSE
cls.rse1 = 'MOCK'
cls.rse3 = 'MOCK3'
... | _session
def check_dataset_ok_callback(scope, name, rse, rse_id, rule_id, session=None):
message = {'scope': scope.external,
'name': name,
'rse': rse,
'rse_id': rse_id,
'rule_id': rule_id}
if scope.vo != 'def':
message['vo'] = scope.vo
cal... | 256 | 256 | 16,641 | 36 | 219 | rucio/rucio | lib/rucio/tests/test_rule.py | Python | TestReplicationRuleCore | TestReplicationRuleCore | 144 | 1,216 | 144 | 147 | 363fd4240b5c025f03f5ed231662940b45bb98c3 | bigcode/the-stack | train |
acdd6309af02e31e55448bfd | train | function | def create_files(nrfiles, scope, rse_id, bytes_=1):
"""
Creates a number of test files and add replicas to rse
:param nrfiles: Number of files to create
:param scope: Scope to create the files in
:param rse_id: RSE to add the replica to
:param bytes_: Bytes of each file
:returns: ... | def create_files(nrfiles, scope, rse_id, bytes_=1):
| """
Creates a number of test files and add replicas to rse
:param nrfiles: Number of files to create
:param scope: Scope to create the files in
:param rse_id: RSE to add the replica to
:param bytes_: Bytes of each file
:returns: List of dict
"""
if config_get_bool('c... | .constants import DIDType, OBSOLETE, RuleState, LockState
from rucio.db.sqla.session import transactional_session
from rucio.tests.common import rse_name_generator, account_name_generator
from rucio.tests.common_server import get_vo
LOG = getLogger(__name__)
def create_files(nrfiles, scope, rse_id, bytes_=1):
| 79 | 79 | 266 | 17 | 62 | rucio/rucio | lib/rucio/tests/test_rule.py | Python | create_files | create_files | 81 | 106 | 81 | 81 | cda10ba9758a5a0285c4d083a5488a5409f0e2ba | bigcode/the-stack | train |
83e38bd382613827cffc3fb1 | train | function | def tag_generator(size=8, chars=string.ascii_uppercase):
return ''.join(random.choice(chars) for x in range(size))
| def tag_generator(size=8, chars=string.ascii_uppercase):
| return ''.join(random.choice(chars) for x in range(size))
| add_replica(rse_id=rse_id, scope=scope, name=file, bytes_=bytes_, account=jdoe)
files.append({'scope': scope, 'name': file, 'bytes': bytes_})
return files
def tag_generator(size=8, chars=string.ascii_uppercase):
| 64 | 64 | 29 | 15 | 48 | rucio/rucio | lib/rucio/tests/test_rule.py | Python | tag_generator | tag_generator | 109 | 110 | 109 | 109 | 85afb1adcd2ae76662bfa07a24810cd0ab9ca299 | bigcode/the-stack | train |
60630b2914581a3aef8ad844 | train | class | @pytest.mark.noparallel(reason='uses pre-defined RSE')
class TestReplicationRuleClient(unittest.TestCase):
@classmethod
def setUpClass(cls):
if config_get_bool('common', 'multi_vo', raise_exception=False, default=False):
cls.vo = {'vo': get_vo()}
else:
cls.vo = {}
... | @pytest.mark.noparallel(reason='uses pre-defined RSE')
class TestReplicationRuleClient(unittest.TestCase):
@classmethod
| def setUpClass(cls):
if config_get_bool('common', 'multi_vo', raise_exception=False, default=False):
cls.vo = {'vo': get_vo()}
else:
cls.vo = {}
# Add test RSE
cls.rse1 = 'MOCK'
cls.rse3 = 'MOCK3'
cls.rse4 = 'MOCK4'
cls.rse5 = 'MOCK5'
... | account)
mktree(scope, account)
rule_ids = add_rule(dids=[{'scope': scope, 'name': 'container1213'}], copies=1, rse_expression='MOCK|MOCK3|MOCK4|MOCK5', grouping='NONE',
account=account, weight=None, lifetime=None, locked=False, subscription_id=None)
rule = get_rule(... | 256 | 256 | 2,339 | 27 | 229 | rucio/rucio | lib/rucio/tests/test_rule.py | Python | TestReplicationRuleClient | TestReplicationRuleClient | 1,219 | 1,399 | 1,219 | 1,222 | 4e78c80fd93057499bf7e36d28d8e0feae811055 | bigcode/the-stack | train |
f82edc6efd2bb89314f5b14e | train | function | @transactional_session
def check_dataset_ok_callback(scope, name, rse, rse_id, rule_id, session=None):
message = {'scope': scope.external,
'name': name,
'rse': rse,
'rse_id': rse_id,
'rule_id': rule_id}
if scope.vo != 'def':
message['vo'] = sco... | @transactional_session
def check_dataset_ok_callback(scope, name, rse, rse_id, rule_id, session=None):
| message = {'scope': scope.external,
'name': name,
'rse': rse,
'rse_id': rse_id,
'rule_id': rule_id}
if scope.vo != 'def':
message['vo'] = scope.vo
callbacks = session.query(models.Message.id).filter(models.Message.payload == json.dumps(mes... | ': bytes_})
return files
def tag_generator(size=8, chars=string.ascii_uppercase):
return ''.join(random.choice(chars) for x in range(size))
@transactional_session
def check_dataset_ok_callback(scope, name, rse, rse_id, rule_id, session=None):
| 64 | 64 | 123 | 27 | 37 | rucio/rucio | lib/rucio/tests/test_rule.py | Python | check_dataset_ok_callback | check_dataset_ok_callback | 113 | 126 | 113 | 114 | 30be7d6e98525c7fd34733088dd71c5bcfa96053 | bigcode/the-stack | train |
fc1c717721eeb0c35e5eaeef | train | function | @transactional_session
def check_rule_progress_callback(scope, name, progress, rule_id, session=None):
message = {'scope': scope.external,
'name': name,
'rule_id': rule_id,
'progress': progress}
if scope.vo != 'def':
message['vo'] = scope.vo
callbacks = ... | @transactional_session
def check_rule_progress_callback(scope, name, progress, rule_id, session=None):
| message = {'scope': scope.external,
'name': name,
'rule_id': rule_id,
'progress': progress}
if scope.vo != 'def':
message['vo'] = scope.vo
callbacks = session.query(models.Message.id).filter(models.Message.payload == json.dumps(message)).all()
if cal... | = scope.vo
callbacks = session.query(models.Message.id).filter(models.Message.payload == json.dumps(message)).all()
if len(callbacks) > 0:
return True
return False
@transactional_session
def check_rule_progress_callback(scope, name, progress, rule_id, session=None):
| 64 | 64 | 100 | 22 | 41 | rucio/rucio | lib/rucio/tests/test_rule.py | Python | check_rule_progress_callback | check_rule_progress_callback | 129 | 141 | 129 | 130 | f8cd29957cdcdb71ff585d1d64b3e0e40a4c711c | bigcode/the-stack | train |
db92dd6e12260f9be47c982a | train | function | @pytest.mark.noparallel(reason='Asynchronos behavior when loading locks')
def test_detach_dataset_lock_removal(did_client, did_factory, root_account, rse_factory, vo):
rse, rse_id = rse_factory.make_posix_rse()
file = did_factory.upload_test_file(rse)
dataset_internal = did_factory.make_dataset()
contai... | @pytest.mark.noparallel(reason='Asynchronos behavior when loading locks')
def test_detach_dataset_lock_removal(did_client, did_factory, root_account, rse_factory, vo):
| rse, rse_id = rse_factory.make_posix_rse()
file = did_factory.upload_test_file(rse)
dataset_internal = did_factory.make_dataset()
container_internal = did_factory.make_container()
# make all scopes external
file, dataset, container = ({'scope': did['scope'].external, 'name': did['name']} for di... | ', weight='fakeweight', lifetime=150, locked=True, subscription_id=None, ask_approval=True)[0]
rule = self.rule_client.get_replication_rule(rule_id)
assert rule['state'] == RuleState.WAITING_APPROVAL.name
self.rule_client.approve_replication_rule(rule_id)
rule = self.rule_client.get_repl... | 131 | 131 | 437 | 40 | 90 | rucio/rucio | lib/rucio/tests/test_rule.py | Python | test_detach_dataset_lock_removal | test_detach_dataset_lock_removal | 1,402 | 1,432 | 1,402 | 1,403 | 476a9c02f0eba3df50ac90ff1edbc679ba7d1e94 | bigcode/the-stack | train |
aa5bc1ce7683effa4d0cd26e | train | class | @params_type(FcParameters)
@quantization('float32')
class LinearFloat32(KernelBase):
@classmethod
def execute(cls, params,
in_tensors,
qrec: QuantizationRecordBase,
**kwargs):
details = kwargs.get('details')
# qrec is set by default to Float32Quant... | @params_type(FcParameters)
@quantization('float32')
class LinearFloat32(KernelBase):
@classmethod
| def execute(cls, params,
in_tensors,
qrec: QuantizationRecordBase,
**kwargs):
details = kwargs.get('details')
# qrec is set by default to Float32QuantizationRecord if None
if qrec is None or isinstance(qrec, Float32QuantizationRecord):
... | # You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import logging
import numpy as np
from graph.types import FcParameters
from quantization.float32.float32_quantization import \
Float32QuantizationRecord, Float32Scala... | 148 | 148 | 495 | 26 | 122 | bot-motion/gap_sdk | tools/nntool/quantization/float32/kernels/linear.py | Python | LinearFloat32 | LinearFloat32 | 29 | 81 | 29 | 32 | c75ed7e48e2b0a542d69e9f8a1295b65a0aa7217 | bigcode/the-stack | train |
8b5ab844be9d2d8398d8960f | train | class | class GenericArtifactsContentClientCompositeOperations(object):
"""
This class provides a wrapper around :py:class:`~oci.generic_artifacts_content.GenericArtifactsContentClient` and offers convenience methods
for operations that would otherwise need to be chained together. For example, instead of performing... | class GenericArtifactsContentClientCompositeOperations(object):
| """
This class provides a wrapper around :py:class:`~oci.generic_artifacts_content.GenericArtifactsContentClient` and offers convenience methods
for operations that would otherwise need to be chained together. For example, instead of performing an action
on a resource (e.g. launching an instance, creati... | pl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
import oci # noqa: F401
from oci.util import WAIT_RESOURCE_NOT_FOUND # noqa: F401
class GenericArtifactsContentClientCompositeOperations(object):
| 64 | 64 | 168 | 9 | 54 | Manny27nyc/oci-python-sdk | src/oci/generic_artifacts_content/generic_artifacts_content_client_composite_operations.py | Python | GenericArtifactsContentClientCompositeOperations | GenericArtifactsContentClientCompositeOperations | 9 | 24 | 9 | 9 | 443e4a56f7599ea033bc0933f8516076ba5c2d26 | bigcode/the-stack | train |
8579c8da6ba9b6e1e06f79df | train | function | def get_tong(sentence):
if get_tong_pinglv(sentence) or get_fan(sentence) or get_xingzhi(sentence):
return True
return False
| def get_tong(sentence):
| if get_tong_pinglv(sentence) or get_fan(sentence) or get_xingzhi(sentence):
return True
return False
| 阵|一直|持续).*(疼|痛)|一阵阵.*(痛|疼)|阵发性|持续性'
if re.search(cc,sentence) is not None:
aa = re.search(cc,sentence).span()
return True
return False
def get_tong(sentence):
| 64 | 64 | 36 | 6 | 57 | KarrXie/CDial-GPT | data/test/evaluate_new.py | Python | get_tong | get_tong | 70 | 73 | 70 | 70 | 7d52df5c037aab95cbf9b291379101c3b56f2e61 | bigcode/the-stack | train |
0949dcbd4f94a66313866e33 | train | function | def get_time(sentence):
aa = "(情况|症状|痛|发病|病|感觉|疼|这样|不舒服|大约).*?(多久|多长时间|几周了?|几天了?)"
bb = "(,|。|、|?)(多长时间了|多久了|有多久了|有多长时间了)|^(多久了|多长时间了|有多久了|有多长时间了|几天了|几周了)"
cc = "有多长时间|有多久"
# match_need = "多久了?|多长时间了?|几天了?|几周了?|多久了|多长时间了|几天了|几周了"
if re.search(aa,sentence) is not None or re.search(bb,sentence) is not... | def get_time(sentence):
| aa = "(情况|症状|痛|发病|病|感觉|疼|这样|不舒服|大约).*?(多久|多长时间|几周了?|几天了?)"
bb = "(,|。|、|?)(多长时间了|多久了|有多久了|有多长时间了)|^(多久了|多长时间了|有多久了|有多长时间了|几天了|几周了)"
cc = "有多长时间|有多久"
# match_need = "多久了?|多长时间了?|几天了?|几周了?|多久了|多长时间了|几天了|几周了"
if re.search(aa,sentence) is not None or re.search(bb,sentence) is not None:
return Tr... | is not None:
aa = re.search(cc,sentence).span()
return True
return False
def get_tong(sentence):
if get_tong_pinglv(sentence) or get_fan(sentence) or get_xingzhi(sentence):
return True
return False
def get_time(sentence):
| 64 | 64 | 192 | 5 | 58 | KarrXie/CDial-GPT | data/test/evaluate_new.py | Python | get_time | get_time | 76 | 83 | 76 | 76 | dc42e7e6d858d78ecefe365688e8291d6857a98c | bigcode/the-stack | train |
ce2b5771f93e65c3b167ca58 | train | function | def get_youyin(sentence):
aa = "(吃早饭|吃饭规律|三餐规律|饮食规律|作息规律|辣|油炸|熬夜|豆类|油腻|生冷|煎炸|浓茶|喝酒|抽烟|吃的多|暴饮暴食|不容易消化的食物|情绪稳定|精神紧张|夜宵).*?(吗|啊?|呢?|么|嘛?)"
bb = "吃得过多过饱|(有没有吃|最近吃|喜欢吃|经常进食|经常吃).*?(辣|油炸|油腻|生冷|煎炸|豆类|不容易消化的食物|夜宵)"
cc = "(工作压力|精神压力|压力).*?(大不大|大吗)|(心情|情绪|精神).*(怎么样|怎样|如何)|(活动量|运动|锻炼).*?(大|多|少|多不多|咋样|怎么样|怎样).*?(吗|呢)"
... | def get_youyin(sentence):
| aa = "(吃早饭|吃饭规律|三餐规律|饮食规律|作息规律|辣|油炸|熬夜|豆类|油腻|生冷|煎炸|浓茶|喝酒|抽烟|吃的多|暴饮暴食|不容易消化的食物|情绪稳定|精神紧张|夜宵).*?(吗|啊?|呢?|么|嘛?)"
bb = "吃得过多过饱|(有没有吃|最近吃|喜欢吃|经常进食|经常吃).*?(辣|油炸|油腻|生冷|煎炸|豆类|不容易消化的食物|夜宵)"
cc = "(工作压力|精神压力|压力).*?(大不大|大吗)|(心情|情绪|精神).*(怎么样|怎样|如何)|(活动量|运动|锻炼).*?(大|多|少|多不多|咋样|怎么样|怎样).*?(吗|呢)"
if re.search(aa,senten... | ], pred_utt, weights=(0.25, 0.25, 0.25, 0.25),
smoothing_function=SmoothingFunction().method7)
else:
bleu_ave_utt = 0
bleu_ave += bleu_ave_utt
bleu_ave /= turns
return bleu_ave
def get_youyin(sentence):
| 79 | 79 | 265 | 6 | 72 | KarrXie/CDial-GPT | data/test/evaluate_new.py | Python | get_youyin | get_youyin | 30 | 36 | 30 | 30 | 1b42fd13d4488c6bf7a9b4cd26bc485169a3289b | bigcode/the-stack | train |
97e09e161eea1a6540de991d | train | class | class KD_Metric():
def __init__(self):
self._pred_true = 0
self._total_pred = 0
self._total_true = 0
self.norm_dict = entity_dict
def reset(self):
self._pred_true = 0
self._total_pred = 0
self._total_true = 0
def get_metric(self, reset=False):
... | class KD_Metric():
| def __init__(self):
self._pred_true = 0
self._total_pred = 0
self._total_true = 0
self.norm_dict = entity_dict
def reset(self):
self._pred_true = 0
self._total_pred = 0
self._total_true = 0
def get_metric(self, reset=False):
rec, acc, f1 = 0.... | 了|有多久了|有多长时间了)|^(多久了|多长时间了|有多久了|有多长时间了|几天了|几周了)"
cc = "有多长时间|有多久"
# match_need = "多久了?|多长时间了?|几天了?|几周了?|多久了|多长时间了|几天了|几周了"
if re.search(aa,sentence) is not None or re.search(bb,sentence) is not None:
return True
return False
class KD_Metric():
| 129 | 129 | 430 | 5 | 123 | KarrXie/CDial-GPT | data/test/evaluate_new.py | Python | KD_Metric | KD_Metric | 86 | 138 | 86 | 86 | 44debe73cf9b403805ea3eddefb5c5a1a29a74e5 | bigcode/the-stack | train |
56b936b5d95e1a92672be874 | train | function | def get_xingzhi(sentence):
cc = '是哪种疼|怎么样的疼|绞痛|钝痛|隐痛|胀痛|隐隐作痛|疼痛.*性质|(性质|什么样).*(的|得)(痛|疼)'
if re.search(cc,sentence) is not None:
return True
return False
| def get_xingzhi(sentence):
| cc = '是哪种疼|怎么样的疼|绞痛|钝痛|隐痛|胀痛|隐隐作痛|疼痛.*性质|(性质|什么样).*(的|得)(痛|疼)'
if re.search(cc,sentence) is not None:
return True
return False
| 什么位置|哪个部位|哪个位置|哪一块|那个部位痛|肚脐眼以上|描述一下位置|具体部位|具体位置'
if re.search(cc,sentence) is not None:
return True
return False
def get_xingzhi(sentence):
| 64 | 64 | 78 | 7 | 56 | KarrXie/CDial-GPT | data/test/evaluate_new.py | Python | get_xingzhi | get_xingzhi | 46 | 50 | 46 | 46 | 9e7d34d6e13ab5f606d27d71419cfa0888a5f516 | bigcode/the-stack | train |
f4c6d94330148f809eebc661 | train | function | def get_tong_pinglv(sentence):
cc = '持续的疼|疼一会儿会自行缓解|持续的,还是阵发|症状减轻了没|(疼|痛).*轻|现在没有症状了吗|现在还有症状吗|(一阵一阵|一直|持续).*(疼|痛)|一阵阵.*(痛|疼)|阵发性|持续性'
if re.search(cc,sentence) is not None:
aa = re.search(cc,sentence).span()
return True
return False
| def get_tong_pinglv(sentence):
| cc = '持续的疼|疼一会儿会自行缓解|持续的,还是阵发|症状减轻了没|(疼|痛).*轻|现在没有症状了吗|现在还有症状吗|(一阵一阵|一直|持续).*(疼|痛)|一阵阵.*(痛|疼)|阵发性|持续性'
if re.search(cc,sentence) is not None:
aa = re.search(cc,sentence).span()
return True
return False
| *(疼|痛|不舒服|不适)'
if re.search(cc,sentence) is not None:
aa = re.search(cc,sentence).span()
if aa[1] - aa[0] <20:
return True
return False
def get_tong_pinglv(sentence):
| 64 | 64 | 118 | 8 | 55 | KarrXie/CDial-GPT | data/test/evaluate_new.py | Python | get_tong_pinglv | get_tong_pinglv | 62 | 67 | 62 | 62 | 59f548a00b39887a91094d61a2ded90e308849e2 | bigcode/the-stack | train |
853fa164199aa7494d808f89 | train | function | def get_location(sentence):
cc = '哪个部位|哪个位置|哪里痛|什么部位|什么位置|哪个部位|哪个位置|哪一块|那个部位痛|肚脐眼以上|描述一下位置|具体部位|具体位置'
if re.search(cc,sentence) is not None:
return True
return False
| def get_location(sentence):
| cc = '哪个部位|哪个位置|哪里痛|什么部位|什么位置|哪个部位|哪个位置|哪一块|那个部位痛|肚脐眼以上|描述一下位置|具体部位|具体位置'
if re.search(cc,sentence) is not None:
return True
return False
| |锻炼).*?(大|多|少|多不多|咋样|怎么样|怎样).*?(吗|呢)"
if re.search(aa,sentence) or re.search(bb, sentence) or re.search(cc, sentence):
return True
return False
def get_location(sentence):
| 64 | 64 | 80 | 5 | 58 | KarrXie/CDial-GPT | data/test/evaluate_new.py | Python | get_location | get_location | 39 | 43 | 39 | 39 | ebc7daac84a92be9c710e0a15833758daa216b3b | bigcode/the-stack | train |
878a1321145db27ce3ad0b1b | train | function | def clac_sentence_metric(ground_truth, predict):
assert len(ground_truth) == len(predict)
kdm = KD_Metric()
for k, sentence in enumerate(ground_truth):
kdm(predict[k], sentence)
kd_metric = kdm.get_metric()
bleu_ave = get_bleu_ave(predict, ground_truth)
pred = []
for index in range(l... | def clac_sentence_metric(ground_truth, predict):
| assert len(ground_truth) == len(predict)
kdm = KD_Metric()
for k, sentence in enumerate(ground_truth):
kdm(predict[k], sentence)
kd_metric = kdm.get_metric()
bleu_ave = get_bleu_ave(predict, ground_truth)
pred = []
for index in range(len(predict)):
pred.append(" ".join(predic... | en_to_entity_set(hypo)
self._total_true += len(ref_list)
self._total_pred += len(hypo_list)
for entity in hypo_list:
if entity in ref_list:
self._pred_true += 1
def clac_sentence_metric(ground_truth, predict):
| 64 | 64 | 111 | 11 | 52 | KarrXie/CDial-GPT | data/test/evaluate_new.py | Python | clac_sentence_metric | clac_sentence_metric | 141 | 151 | 141 | 141 | 9363bd6bcf559229e93f898f950f00f1ac30dc35 | bigcode/the-stack | train |
52858b84bb05c5936c958ba5 | train | function | def eval_output(submit, reference):
# submit = []
# with open(hp, "r", encoding="utf-8") as f:
# # submit = pickle.load(f)
# for line in f.readlines():
# submit.append(line.strip())
# with open(rf, "rb") as f:
# reference = pickle.load(f)
f1, bleuave = clac_sentence_m... | def eval_output(submit, reference):
# submit = []
# with open(hp, "r", encoding="utf-8") as f:
# # submit = pickle.load(f)
# for line in f.readlines():
# submit.append(line.strip())
# with open(rf, "rb") as f:
# reference = pickle.load(f)
| f1, bleuave = clac_sentence_metric(reference, submit)
print('F1:{:.4f}'.format(f1*100))
print('BLEU-ave:{:.4f}'.format(bleuave*100))
ave = (bleuave+f1)/2*100
return ave, f1, bleuave
| def eval_output(submit, reference):
# submit = []
# with open(hp, "r", encoding="utf-8") as f:
# # submit = pickle.load(f)
# for line in f.readlines():
# submit.append(line.strip())
# with open(rf, "rb") as f:
# reference = pickle.load(f)
| 81 | 64 | 157 | 81 | 0 | KarrXie/CDial-GPT | data/test/evaluate_new.py | Python | eval_output | eval_output | 154 | 166 | 154 | 161 | 8e724fa1bd13150f2e1f4195bcd80e44c215fcb2 | bigcode/the-stack | train |
9bb158d11e95e7c57419c857 | train | function | def get_bleu_ave(pred, target):
turns = len(target)
bleu_ave = 0
for index in range(turns):
pred_utt = pred[index]
target_utt = target[index]
min_len = min(len(pred_utt), len(target_utt))
if min_len >= 4:
bleu_ave_utt = sentence_bleu([target_utt], pred_utt, weight... | def get_bleu_ave(pred, target):
| turns = len(target)
bleu_ave = 0
for index in range(turns):
pred_utt = pred[index]
target_utt = target[index]
min_len = min(len(pred_utt), len(target_utt))
if min_len >= 4:
bleu_ave_utt = sentence_bleu([target_utt], pred_utt, weights=(0.25, 0.25, 0.25, 0.25),
... | '斯达舒', '泮托拉唑': '泮托拉唑'}
import pickle
from nltk.translate.bleu_score import sentence_bleu
from nltk.translate.bleu_score import SmoothingFunction
import argparse
import re
def get_bleu_ave(pred, target):
| 64 | 64 | 158 | 10 | 53 | KarrXie/CDial-GPT | data/test/evaluate_new.py | Python | get_bleu_ave | get_bleu_ave | 13 | 27 | 13 | 13 | 7e3981a870ea44f51fe66d575be90c874fa6a46c | bigcode/the-stack | train |
606b4dea1ad3190b0b0ddebd | train | function | def get_fan(sentence):
cc = '(饭.*?前|吃东西前|餐前).*(疼|痛|不舒服|不适)|(饭.*?后|吃东西后|餐后).*(疼|痛|不舒服|不适)|(早上|早晨|夜里|半夜|晚饭).*(疼|痛|不舒服|不适)'
if re.search(cc,sentence) is not None:
aa = re.search(cc,sentence).span()
if aa[1] - aa[0] <20:
return True
return False
| def get_fan(sentence):
| cc = '(饭.*?前|吃东西前|餐前).*(疼|痛|不舒服|不适)|(饭.*?后|吃东西后|餐后).*(疼|痛|不舒服|不适)|(早上|早晨|夜里|半夜|晚饭).*(疼|痛|不舒服|不适)'
if re.search(cc,sentence) is not None:
aa = re.search(cc,sentence).span()
if aa[1] - aa[0] <20:
return True
return False
| �痛|钝痛|隐痛|胀痛|隐隐作痛|疼痛.*性质|(性质|什么样).*(的|得)(痛|疼)'
if re.search(cc,sentence) is not None:
return True
return False
def get_fan(sentence):
| 64 | 64 | 127 | 6 | 57 | KarrXie/CDial-GPT | data/test/evaluate_new.py | Python | get_fan | get_fan | 53 | 59 | 53 | 53 | 7a8cb14d87b539166519890f0a6bd3f2ab446d76 | bigcode/the-stack | train |
d903307f525469931aa75318 | train | class | class TablesHeightTestCase(unittest.TestCase):
def test_width_returns_none_if_value_passed_is_none(self):
result = tables._height(None)
self.assertEqual(result, None)
def test_width_returns_values_passed_if_string_and_ends_with_percent(self):
result = tables._height("100%")
sel... | class TablesHeightTestCase(unittest.TestCase):
| def test_width_returns_none_if_value_passed_is_none(self):
result = tables._height(None)
self.assertEqual(result, None)
def test_width_returns_values_passed_if_string_and_ends_with_percent(self):
result = tables._height("100%")
self.assertEqual(result, "100%")
def test_widt... | _percent(self):
result = tables._width("100")
self.assertEqual(type(result), float)
def test_width_returns_float_if_string_contains_string_of_number(self):
result = tables._width("130")
self.assertEqual(result, 130.0)
class TablesHeightTestCase(unittest.TestCase):
| 64 | 64 | 147 | 9 | 55 | fbernhart/xhtml2pdf | tests/test_tables.py | Python | TablesHeightTestCase | TablesHeightTestCase | 28 | 44 | 28 | 29 | 1fd7982727837a69439be4f54a0e69c0754fb616 | bigcode/the-stack | train |
a152e77293215c87c6dda646 | train | class | class TableDataTestCase(unittest.TestCase):
def setUp(self):
self.sut = tables.TableData
def test_init_defines_variables(self):
instance = self.sut()
self.assertEqual(instance.data, [])
self.assertEqual(instance.styles, [])
self.assertEqual(instance.span, [])
se... | class TableDataTestCase(unittest.TestCase):
| def setUp(self):
self.sut = tables.TableData
def test_init_defines_variables(self):
instance = self.sut()
self.assertEqual(instance.data, [])
self.assertEqual(instance.styles, [])
self.assertEqual(instance.span, [])
self.assertEqual(instance.mode, "")
sel... | ends_with_percent(self):
result = tables._width("100%")
self.assertEqual(result, "100%")
def test_width_will_convert_string_to_float_if_string_passed_in_doesnt_end_with_percent(self):
result = tables._width("100")
self.assertEqual(type(result), float)
def test_width_returns_flo... | 256 | 256 | 2,973 | 9 | 247 | fbernhart/xhtml2pdf | tests/test_tables.py | Python | TableDataTestCase | TableDataTestCase | 47 | 287 | 47 | 48 | 5e53a9a8b854ae33ea2dac69db75eb99b91f8fa2 | bigcode/the-stack | train |
6fea74a1ccad934cb664bb73 | train | class | class PisaTagTDTestCase(unittest.TestCase):
def test_td_tag_doesnt_collapse_when_empty(self):
dom = minidom.parseString("<td></td>")
element = dom.getElementsByTagName("td")[0]
attrs = AttrContainer({
'align': None,
'colspan': None,
'rowspan': None,
... | class PisaTagTDTestCase(unittest.TestCase):
| def test_td_tag_doesnt_collapse_when_empty(self):
dom = minidom.parseString("<td></td>")
element = dom.getElementsByTagName("td")[0]
attrs = AttrContainer({
'align': None,
'colspan': None,
'rowspan': None,
'width': None,
'valign': N... | .assertEqual(context.frag.borderLeftStyle, "solid")
self.assertEqual(context.frag.borderRightStyle, "solid")
self.assertEqual(context.frag.borderTopStyle, "solid")
self.assertEqual(context.frag.borderBottomStyle, "solid")
class PisaTagTDTestCase(unittest.TestCase):
| 64 | 64 | 194 | 10 | 54 | fbernhart/xhtml2pdf | tests/test_tables.py | Python | PisaTagTDTestCase | PisaTagTDTestCase | 342 | 367 | 342 | 343 | 57fbe737478658c63fc444898421a880175bf1b9 | bigcode/the-stack | train |
f6d9f28888a9d4179e077c62 | train | class | class PisaTagTableTestCase(unittest.TestCase):
def setUp(self):
self.element = self._getElement("rootElement")
self.attrs = AttrContainer({"border": "", "bordercolor": "", "cellpadding": "", "align": "",
"repeat": "", "width": ""})
def _getElement(self, tagN... | class PisaTagTableTestCase(unittest.TestCase):
| def setUp(self):
self.element = self._getElement("rootElement")
self.attrs = AttrContainer({"border": "", "bordercolor": "", "cellpadding": "", "align": "",
"repeat": "", "width": ""})
def _getElement(self, tagName, body="filler"):
dom = minidom.parse... | instance = self.sut()
instance.add_cell_styles(context, (0, 1), (3, 5), mode="tr")
self.assertEqual(instance.styles[0], ('LINEABOVE', (0, 1), (3, 1), '3px', 'black', 'squared'))
self.assertEqual(instance.styles[1], ('LINEBEFORE', (0, 1), (0, 5), '3px', 'black', 'squared'))
self.a... | 188 | 189 | 630 | 10 | 178 | fbernhart/xhtml2pdf | tests/test_tables.py | Python | PisaTagTableTestCase | PisaTagTableTestCase | 290 | 339 | 290 | 291 | 666eeb42697fc676d5e08c7253faee69fbd34073 | bigcode/the-stack | train |
7b149f28655b0f4c4babee6e | train | class | class TablesWidthTestCase(unittest.TestCase):
def test_width_returns_none_if_value_passed_is_none(self):
result = tables._width(None)
self.assertEqual(result, None)
def test_width_returns_values_passed_if_string_and_ends_with_percent(self):
result = tables._width("100%")
self.a... | class TablesWidthTestCase(unittest.TestCase):
| def test_width_returns_none_if_value_passed_is_none(self):
result = tables._width(None)
self.assertEqual(result, None)
def test_width_returns_values_passed_if_string_and_ends_with_percent(self):
result = tables._width("100%")
self.assertEqual(result, "100%")
def test_width_... | import unittest
from xml.dom import minidom
from xhtml2pdf import tables
from xhtml2pdf.context import pisaContext
from xhtml2pdf.parser import AttrContainer
class TablesWidthTestCase(unittest.TestCase):
| 48 | 64 | 151 | 9 | 38 | fbernhart/xhtml2pdf | tests/test_tables.py | Python | TablesWidthTestCase | TablesWidthTestCase | 9 | 25 | 9 | 10 | d2d43c50983391eb4721eb6ce382b542890dde4a | bigcode/the-stack | train |
374a6208c7503313e9e3e4e2 | train | class | class XParagraphAppend(XInterface_8f010a43):
"""
allows inserting and appending paragraphs.
**since**
LibreOffice 4.0
See Also:
`API XParagraphAppend <https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XParagraphAppend.html>`_
"""
__ooo_ns_... | class XParagraphAppend(XInterface_8f010a43):
| """
allows inserting and appending paragraphs.
**since**
LibreOffice 4.0
See Also:
`API XParagraphAppend <https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1text_1_1XParagraphAppend.html>`_
"""
__ooo_ns__: str = 'com.sun.star.text'
__ooo_full_n... | # this is a auto generated file generated by Cheetah
# Libre Office Version: 7.3
# Namespace: com.sun.star.text
import typing
from abc import abstractmethod
from ..uno.x_interface import XInterface as XInterface_8f010a43
if typing.TYPE_CHECKING:
from ..beans.property_values import PropertyValues as PropertyValues_d... | 116 | 116 | 388 | 13 | 102 | Amourspirit/ooo_uno_tmpl | ooobuild/lo/text/x_paragraph_append.py | Python | XParagraphAppend | XParagraphAppend | 28 | 69 | 28 | 28 | 1a2759df578e48e83fe23ae5017938aa2c12f3bd | bigcode/the-stack | train |
edf80caa9d9c785128baa777 | train | function | def get_FB_PLAYER_TABLE_IDS(verbose=False) -> list:
prefix = "stats_"
sfxs = [
"_ks_dom_lg",
"_ks_dom_cup",
"_ks_intl_cup",
"_ks_expanded",
"_ks_collapsed",
"_dom_lg",
"_dom_cup",
]
categories = ["standard", "shooting", "passing", "playing_time", "... | def get_FB_PLAYER_TABLE_IDS(verbose=False) -> list:
| prefix = "stats_"
sfxs = [
"_ks_dom_lg",
"_ks_dom_cup",
"_ks_intl_cup",
"_ks_expanded",
"_ks_collapsed",
"_dom_lg",
"_dom_cup",
]
categories = ["standard", "shooting", "passing", "playing_time", "misc"]
table_ids = []
for cat in categories:... | ",
"pitching_value",
"pitching_postseason",
"batting_standard",
"batting_value",
"batting_postseason",
"standard_fielding",
"appearances",
"br-salaries",
]
def get_FB_PLAYER_TABLE_IDS(verbose=False) -> list:
| 64 | 64 | 154 | 12 | 52 | AnandIJain/sip | sips/macros/sports_ref.py | Python | get_FB_PLAYER_TABLE_IDS | get_FB_PLAYER_TABLE_IDS | 130 | 151 | 130 | 130 | 12ff3ddd9a73311c143cfb679d6746b2211138c5 | bigcode/the-stack | train |
d7f9fe1a4e35fced818fd9b8 | train | class | class HasWebServer(object):
"""
HasWebServer represents the WebServer attached to some top-level objects.
"""
""" Configuration specific to itop """
foreign_key = {'id': 'webserver_id', 'name': 'webserver_name', 'table': 'WebServer'}
def __init__(self):
super(HasWebServer, self).__init... | class HasWebServer(object):
| """
HasWebServer represents the WebServer attached to some top-level objects.
"""
""" Configuration specific to itop """
foreign_key = {'id': 'webserver_id', 'name': 'webserver_name', 'table': 'WebServer'}
def __init__(self):
super(HasWebServer, self).__init__()
# Object's web... |
# pylint: disable=too-many-instance-attributes, invalid-name
"""
HasWebServer is a mixin representing the webserver attached to some of the objects.
"""
from itopapi.model.prototype import ItopapiPrototype
__version__ = '1.0'
__authors__ = ['Julien Nauroy <julien.nauroy@u-psud.fr>']
class HasWebServer(object):
| 85 | 85 | 285 | 6 | 79 | JulienNauroy/python-itop-api | itopapi/model/features/hasWebServer.py | Python | HasWebServer | HasWebServer | 13 | 46 | 13 | 13 | ae584dacbf9352f0b3209824d445ccd7b137e724 | bigcode/the-stack | train |
907ecb7b21de9ae005a04407 | train | function | def solve(x, k):
return input() == k
| def solve(x, k):
| return input() == k
| def solve(x, k):
| 6 | 64 | 13 | 6 | 0 | HarshitRuwali/HackerRank-Solutions | Python/input().py | Python | solve | solve | 1 | 2 | 1 | 1 | 9744591d5992ac4c1c537a5b1ee18c6085260bbc | bigcode/the-stack | train |
efda85195901acde92260aec | train | function | def main():
x, k = map(int, raw_input().split())
print(solve(x, k))
| def main():
| x, k = map(int, raw_input().split())
print(solve(x, k))
| def solve(x, k):
return input() == k
def main():
| 16 | 64 | 24 | 3 | 12 | HarshitRuwali/HackerRank-Solutions | Python/input().py | Python | main | main | 5 | 7 | 5 | 5 | d1d7bb29918846352734bf62f6cae4c9e0ce8e2e | bigcode/the-stack | train |
ef23bb73b75551abeec74ef7 | train | class | @admin.register(Word)
class WordAdmin(admin.ModelAdmin):
fields = ("value", "description")
list_display = ("id", "value", )
| @admin.register(Word)
class WordAdmin(admin.ModelAdmin):
| fields = ("value", "description")
list_display = ("id", "value", )
| from django.contrib import admin
from dictionary.models import Word
@admin.register(Word)
class WordAdmin(admin.ModelAdmin):
| 25 | 64 | 33 | 13 | 11 | chiliseed/django-starter-apps | src/dictionary/admin.py | Python | WordAdmin | WordAdmin | 6 | 9 | 6 | 7 | 80fa8617f7b15bada63e73770f553aecbc57b98c | bigcode/the-stack | train |
2d8a01403a9390050baa8cb6 | train | class | class Assess(object):
'''
性能评估指标
'''
def __init__(self):
pass
def accuracy(self,y,y_):
with tf.name_scope('accuracy'):
with tf.name_scope('correct_prediction'):
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
with tf.name_scope('accuracy'):
accuracy = tf.reduce_mean(tf.cast(corre... | class Assess(object):
| '''
性能评估指标
'''
def __init__(self):
pass
def accuracy(self,y,y_):
with tf.name_scope('accuracy'):
with tf.name_scope('correct_prediction'):
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
with tf.name_scope('accuracy'):
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float... | #!/usr/bin/env python
#-*- coding: utf-8 -*-
import tensorflow as tf
class Assess(object):
| 24 | 75 | 251 | 4 | 19 | BoxFishLab/TF.Keras-GAN | GAN-minst/model/assess.py | Python | Assess | Assess | 6 | 35 | 6 | 6 | 6a50fa43b7148c8b5d8ef3801e5589db36443056 | bigcode/the-stack | train |
53e5560ddfa86835c77f39a2 | train | function | def get_index_html(bucket, project, bundle_version, region='ap-southeast-2',
bundle='index.js.gz', default_title=''):
return index_html.format(
bucket=bucket,
project=project,
bundle_version=bundle_version,
region=region,
bundle=bundle,
default_titl... | def get_index_html(bucket, project, bundle_version, region='ap-southeast-2',
bundle='index.js.gz', default_title=''):
| return index_html.format(
bucket=bucket,
project=project,
bundle_version=bundle_version,
region=region,
bundle=bundle,
default_title=default_title
)
| }.amazonaws.com/{bucket}/projects/{project}/bundle/{bundle_version}/{bundle}"
>
</script>
</body>
</html>
'''
def get_index_html(bucket, project, bundle_version, region='ap-southeast-2',
bundle='index.js.gz', default_title=''):
| 63 | 64 | 73 | 31 | 32 | furious-luke/polecat | polecat/project/index.py | Python | get_index_html | get_index_html | 25 | 34 | 25 | 26 | f56ddd826895a3992b584d1e00c7537a0e1996f9 | bigcode/the-stack | train |
3f431174ad7d8e5266fd8bc9 | train | class | class IndexHandler(Handler):
def prepare(self):
self.index_html = self.project.get_index_html()
def match(self, event):
# TODO: Use regex
return event.is_http() and \
event.request.method == 'GET' or \
event.request.path == '/'
async def handle_event(self, eve... | class IndexHandler(Handler):
| def prepare(self):
self.index_html = self.project.get_index_html()
def match(self, event):
# TODO: Use regex
return event.is_http() and \
event.request.method == 'GET' or \
event.request.path == '/'
async def handle_event(self, event):
return (self.ind... | outheast-2',
bundle='index.js.gz', default_title=''):
return index_html.format(
bucket=bucket,
project=project,
bundle_version=bundle_version,
region=region,
bundle=bundle,
default_title=default_title
)
class IndexHandler(Handler):
| 64 | 64 | 84 | 6 | 58 | furious-luke/polecat | polecat/project/index.py | Python | IndexHandler | IndexHandler | 37 | 48 | 37 | 37 | 652b3bbc06e28796ad7babf169bb86b4939b9d93 | bigcode/the-stack | train |
3e539db27ea12226cf476db7 | train | function | def strptime(string, format="%a %b %d %H:%M:%S %Y"):
"""strptime(string, format) -> struct_time
Parse a string to a time tuple according to a format specification.
See the library reference manual for formatting codes
(same as strftime())."""
import _strptime # from the CPython standard librar... | def strptime(string, format="%a %b %d %H:%M:%S %Y"):
| """strptime(string, format) -> struct_time
Parse a string to a time tuple according to a format specification.
See the library reference manual for formatting codes
(same as strftime())."""
import _strptime # from the CPython standard library
return _strptime._strptime(string, format)[0]
| = structseqfield(5)
tm_wday = structseqfield(6)
tm_yday = structseqfield(7)
tm_isdst = structseqfield(8)
def strptime(string, format="%a %b %d %H:%M:%S %Y"):
| 64 | 64 | 93 | 21 | 43 | nanjekyejoannah/pypy | pypy/module/time/app_time.py | Python | strptime | strptime | 20 | 28 | 20 | 20 | a8bffcfe6c5a0a4e1e9ae5eb19632b3906febb31 | bigcode/the-stack | train |
04c557222d6912671d72a782 | train | class | class struct_time:
__metaclass__ = structseqtype
__module__ = 'time'
name = 'time.struct_time'
tm_year = structseqfield(0)
tm_mon = structseqfield(1)
tm_mday = structseqfield(2)
tm_hour = structseqfield(3)
tm_min = structseqfield(4)
tm_sec = structseqfield(5)
tm_w... | class struct_time:
| __metaclass__ = structseqtype
__module__ = 'time'
name = 'time.struct_time'
tm_year = structseqfield(0)
tm_mon = structseqfield(1)
tm_mday = structseqfield(2)
tm_hour = structseqfield(3)
tm_min = structseqfield(4)
tm_sec = structseqfield(5)
tm_wday = structseqfi... | # NOT_RPYTHON
from _structseq import structseqtype, structseqfield
class struct_time:
| 23 | 64 | 133 | 4 | 18 | nanjekyejoannah/pypy | pypy/module/time/app_time.py | Python | struct_time | struct_time | 5 | 18 | 5 | 5 | 66eff42d064ad8c32ccf4430560b20584c704c27 | bigcode/the-stack | train |
3a74de191f06f76ae1a64681 | train | class | class pAdicCappedAbsoluteRingGeneric(pAdicRingGeneric, CappedAbsoluteGeneric):
pass
| class pAdicCappedAbsoluteRingGeneric(pAdicRingGeneric, CappedAbsoluteGeneric):
| pass
| NotImplementedError
#def subfields_of_degree(self, n):
# raise NotImplementedError
class pAdicFixedModRingGeneric(pAdicRingGeneric, FixedModGeneric):
pass
class pAdicCappedAbsoluteRingGeneric(pAdicRingGeneric, CappedAbsoluteGeneric):
| 64 | 64 | 23 | 20 | 43 | vbraun/sage | src/sage/rings/padics/generic_nodes.py | Python | pAdicCappedAbsoluteRingGeneric | pAdicCappedAbsoluteRingGeneric | 361 | 362 | 361 | 361 | 0d5021833d9c39d61ca967737f152d779e4332f4 | bigcode/the-stack | train |
561508095ccd8aed5a2134d1 | train | class | class pAdicCappedRelativeFieldGeneric(pAdicFieldGeneric, CappedRelativeFieldGeneric):
pass
| class pAdicCappedRelativeFieldGeneric(pAdicFieldGeneric, CappedRelativeFieldGeneric):
| pass
| CappedAbsoluteRingGeneric(pAdicRingGeneric, CappedAbsoluteGeneric):
pass
class pAdicCappedRelativeRingGeneric(pAdicRingGeneric, CappedRelativeRingGeneric):
pass
class pAdicCappedRelativeFieldGeneric(pAdicFieldGeneric, CappedRelativeFieldGeneric):
| 64 | 64 | 24 | 21 | 42 | vbraun/sage | src/sage/rings/padics/generic_nodes.py | Python | pAdicCappedRelativeFieldGeneric | pAdicCappedRelativeFieldGeneric | 365 | 366 | 365 | 365 | 8ffe9d47ab391b67c31dc9b57577d026862cb3f8 | bigcode/the-stack | train |
7bebf982f3b25a75a99fba6d | train | class | class pAdicFieldBaseGeneric(pAdicBaseGeneric, pAdicFieldGeneric):
def composite(self, subfield1, subfield2):
r"""
Returns the composite of two subfields of self, i.e., the
largest subfield containing both
INPUT:
- ``self`` -- a `p`-adic field
- ``subfield1`` -- a su... | class pAdicFieldBaseGeneric(pAdicBaseGeneric, pAdicFieldGeneric):
| def composite(self, subfield1, subfield2):
r"""
Returns the composite of two subfields of self, i.e., the
largest subfield containing both
INPUT:
- ``self`` -- a `p`-adic field
- ``subfield1`` -- a subfield
- ``subfield2`` -- a subfield
OUTPUT:
... | default'):
if self.is_capped_relative():
i = 0
a_i = ZZ.random_element(self.prime())
while a_i.is_zero():
i += 1
a_i = ZZ.random_element(self.prime())
return self((self.prime()**i)*(a_i + self.prime()*ZZ.... | 192 | 192 | 642 | 19 | 172 | vbraun/sage | src/sage/rings/padics/generic_nodes.py | Python | pAdicFieldBaseGeneric | pAdicFieldBaseGeneric | 439 | 534 | 439 | 439 | b8eae95f4e7de1c5be9143854c782113ec6e4bcc | bigcode/the-stack | train |
0d62fafec3222c00bf0062f2 | train | class | class CappedRelativeFieldGeneric(CappedRelativeGeneric):#, sage.rings.ring.Field):
pass
| class CappedRelativeFieldGeneric(CappedRelativeGeneric):#, sage.rings.ring.Field):
| pass
| RingGeneric(FloatingPointGeneric):
pass
class FloatingPointFieldGeneric(FloatingPointGeneric):#, sage.rings.ring.Field):
pass
class CappedRelativeRingGeneric(CappedRelativeGeneric):
pass
class CappedRelativeFieldGeneric(CappedRelativeGeneric):#, sage.rings.ring.Field):
| 64 | 64 | 22 | 19 | 44 | vbraun/sage | src/sage/rings/padics/generic_nodes.py | Python | CappedRelativeFieldGeneric | CappedRelativeFieldGeneric | 262 | 263 | 262 | 262 | e4942856bccf57e5551951d568edc10e1a6d7abd | bigcode/the-stack | train |
956f3c70c91ea45f0f8f79e0 | train | class | class FloatingPointRingGeneric(FloatingPointGeneric):
pass
| class FloatingPointRingGeneric(FloatingPointGeneric):
| pass
| ,z in some_tuples(S, 3, tester._max_runs):
tester.assert_(((x + y) + z).is_equal_to(x + (y + z), min(x.precision_absolute(), y.precision_absolute(), z.precision_absolute())))
class FloatingPointRingGeneric(FloatingPointGeneric):
| 63 | 64 | 13 | 10 | 53 | vbraun/sage | src/sage/rings/padics/generic_nodes.py | Python | FloatingPointRingGeneric | FloatingPointRingGeneric | 256 | 257 | 256 | 256 | 8f45b4ceeea04c4f145b6686758beaf31b556a64 | bigcode/the-stack | train |
7d57820719e42af710920bc9 | train | class | class CappedRelativeGeneric(LocalGeneric):
def is_capped_relative(self):
"""
Returns whether this `p`-adic ring bounds precision in a capped
relative fashion.
The relative precision of an element is the power of p modulo
which the unit part of that element is defined. In a ... | class CappedRelativeGeneric(LocalGeneric):
| def is_capped_relative(self):
"""
Returns whether this `p`-adic ring bounds precision in a capped
relative fashion.
The relative precision of an element is the power of p modulo
which the unit part of that element is defined. In a capped
relative ring, the relative ... | 7 + O(5^22)
"""
return True
def _prec_type(self):
"""
Returns the precision handling type.
EXAMPLES::
sage: ZpCA(5)._prec_type()
'capped-abs'
"""
return 'capped-abs'
class CappedRelativeGeneric(LocalGeneric):
| 71 | 71 | 238 | 8 | 63 | vbraun/sage | src/sage/rings/padics/generic_nodes.py | Python | CappedRelativeGeneric | CappedRelativeGeneric | 69 | 104 | 69 | 69 | 8406825bfc4d6ff9719bb33142f813b007a65c1b | bigcode/the-stack | train |
49190eb923d1eaa4b1fd7355 | train | class | class FixedModGeneric(LocalGeneric):
def is_fixed_mod(self):
"""
Returns whether this `p`-adic ring bounds precision in a fixed
modulus fashion.
The absolute precision of an element is the power of p modulo
which that element is defined. In a fixed modulus ring, the
... | class FixedModGeneric(LocalGeneric):
| def is_fixed_mod(self):
"""
Returns whether this `p`-adic ring bounds precision in a fixed
modulus fashion.
The absolute precision of an element is the power of p modulo
which that element is defined. In a fixed modulus ring, the
absolute precision of every element ... | sage: S(5^7)
5^7 + O(5^22)
"""
return True
def _prec_type(self):
"""
Returns the precision handling type.
EXAMPLES::
sage: Zp(5)._prec_type()
'capped-rel'
"""
return 'capped-rel'
class FixedModGeneric(LocalGeneric):
| 79 | 79 | 265 | 7 | 72 | vbraun/sage | src/sage/rings/padics/generic_nodes.py | Python | FixedModGeneric | FixedModGeneric | 106 | 142 | 106 | 106 | 8ee7610869bea8c28b3dd8443026ccaaf9ef97a7 | bigcode/the-stack | train |
18eacba1235166cd94dd093f | train | class | class pAdicCappedRelativeRingGeneric(pAdicRingGeneric, CappedRelativeRingGeneric):
pass
| class pAdicCappedRelativeRingGeneric(pAdicRingGeneric, CappedRelativeRingGeneric):
| pass
| pAdicFixedModRingGeneric(pAdicRingGeneric, FixedModGeneric):
pass
class pAdicCappedAbsoluteRingGeneric(pAdicRingGeneric, CappedAbsoluteGeneric):
pass
class pAdicCappedRelativeRingGeneric(pAdicRingGeneric, CappedRelativeRingGeneric):
| 64 | 64 | 24 | 21 | 42 | vbraun/sage | src/sage/rings/padics/generic_nodes.py | Python | pAdicCappedRelativeRingGeneric | pAdicCappedRelativeRingGeneric | 363 | 364 | 363 | 363 | e439501f954e32f79992d64952f6a90ce0751949 | bigcode/the-stack | train |
bbf8d776bf2f4e20d453759e | train | class | class pAdicRingBaseGeneric(pAdicBaseGeneric, pAdicRingGeneric):
def construction(self):
"""
Returns the functorial construction of self, namely,
completion of the rational numbers with respect a given prime.
Also preserves other information that makes this field unique
(e.g.... | class pAdicRingBaseGeneric(pAdicBaseGeneric, pAdicRingGeneric):
| def construction(self):
"""
Returns the functorial construction of self, namely,
completion of the rational numbers with respect a given prime.
Also preserves other information that makes this field unique
(e.g. precision, rounding, print mode).
EXAMPLES::
... | Error
#def subfields_of_degree(self, n):
# raise NotImplementedError
class pAdicFixedModRingGeneric(pAdicRingGeneric, FixedModGeneric):
pass
class pAdicCappedAbsoluteRingGeneric(pAdicRingGeneric, CappedAbsoluteGeneric):
pass
class pAdicCappedRelativeRingGeneric(pAdicRingGeneric, CappedRelativeRingG... | 176 | 176 | 587 | 19 | 156 | vbraun/sage | src/sage/rings/padics/generic_nodes.py | Python | pAdicRingBaseGeneric | pAdicRingBaseGeneric | 372 | 428 | 372 | 372 | cb9faffb2666a872d52ac1631917e5b48403318b | bigcode/the-stack | train |
e0a9e575bf98a992f3685181 | train | class | class pAdicFixedModRingGeneric(pAdicRingGeneric, FixedModGeneric):
pass
| class pAdicFixedModRingGeneric(pAdicRingGeneric, FixedModGeneric):
| pass
| list):
# raise NotImplementedError
#def subfield_lattice(self):
# raise NotImplementedError
#def subfields_of_degree(self, n):
# raise NotImplementedError
class pAdicFixedModRingGeneric(pAdicRingGeneric, FixedModGeneric):
| 64 | 64 | 21 | 18 | 45 | vbraun/sage | src/sage/rings/padics/generic_nodes.py | Python | pAdicFixedModRingGeneric | pAdicFixedModRingGeneric | 359 | 360 | 359 | 359 | 5a520028bd73fb43c5d6a2a96054dad6879648d6 | bigcode/the-stack | train |
04db0603c8ed60a163cf52ff | train | function | def is_pAdicRing(R):
"""
Returns ``True`` if and only if ``R`` is a `p`-adic ring (not a
field).
EXAMPLES::
sage: is_pAdicRing(Zp(5))
True
sage: is_pAdicRing(RR)
False
"""
return isinstance(R, pAdicRingGeneric)
| def is_pAdicRing(R):
| """
Returns ``True`` if and only if ``R`` is a `p`-adic ring (not a
field).
EXAMPLES::
sage: is_pAdicRing(Zp(5))
True
sage: is_pAdicRing(RR)
False
"""
return isinstance(R, pAdicRingGeneric)
| FloatingPointFieldGeneric(FloatingPointGeneric):#, sage.rings.ring.Field):
pass
class CappedRelativeRingGeneric(CappedRelativeGeneric):
pass
class CappedRelativeFieldGeneric(CappedRelativeGeneric):#, sage.rings.ring.Field):
pass
def is_pAdicRing(R):
| 64 | 64 | 84 | 8 | 55 | vbraun/sage | src/sage/rings/padics/generic_nodes.py | Python | is_pAdicRing | is_pAdicRing | 266 | 278 | 266 | 266 | 5d4c208a8ca0191cdad2ac4281266e96ba09926e | bigcode/the-stack | train |
435fa61085b8cfe2ee42db62 | train | class | class pAdicRingGeneric(pAdicGeneric, EuclideanDomain):
def is_field(self, proof = True):
"""
Returns whether this ring is actually a field, ie ``False``.
EXAMPLES::
sage: Zp(5).is_field()
False
"""
return False
def krull_dimension(self):
... | class pAdicRingGeneric(pAdicGeneric, EuclideanDomain):
| def is_field(self, proof = True):
"""
Returns whether this ring is actually a field, ie ``False``.
EXAMPLES::
sage: Zp(5).is_field()
False
"""
return False
def krull_dimension(self):
r"""
Returns the Krull dimension of self, i.e... | field).
EXAMPLES::
sage: is_pAdicRing(Zp(5))
True
sage: is_pAdicRing(RR)
False
"""
return isinstance(R, pAdicRingGeneric)
class pAdicRingGeneric(pAdicGeneric, EuclideanDomain):
| 64 | 64 | 162 | 15 | 49 | vbraun/sage | src/sage/rings/padics/generic_nodes.py | Python | pAdicRingGeneric | pAdicRingGeneric | 280 | 311 | 280 | 280 | f1bdba913ce7d75111cb592b75c79fff114655f2 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.