code stringlengths 281 23.7M |
|---|
(data=st.data())
def test_overriding_standard_format(data):
expected = '2000-01-01'
schema = {'type': 'string', 'format': 'full-date'}
custom_formats = {'full-date': st.just(expected)}
with pytest.warns(HypothesisWarning, match="Overriding standard format 'full-date'"):
value = data.draw(from_sc... |
class CrossAttention(nn.Module):
def __init__(self, dim, out_dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0):
super().__init__()
self.num_heads = num_heads
self.dim = dim
self.out_dim = out_dim
head_dim = (out_dim // num_heads)
self.scal... |
class FormatsUnmarshaller():
def __init__(self, format_unmarshallers: Optional[FormatUnmarshallersDict]=None, extra_format_unmarshallers: Optional[FormatUnmarshallersDict]=None):
if (format_unmarshallers is None):
format_unmarshallers = {}
self.format_unmarshallers = format_unmarshallers... |
def gen_vocab(input_path: Path, output_path_prefix: Path, model_type='bpe', vocab_size=1000, special_symbols: Optional[List[str]]=None):
arguments = [f'--input={input_path.as_posix()}', f'--model_prefix={output_path_prefix.as_posix()}', f'--model_type={model_type}', f'--vocab_size={vocab_size}', '--character_covera... |
def get_token_by_uuid(uuid, owner=None):
try:
query = AppSpecificAuthToken.select().where((AppSpecificAuthToken.uuid == uuid), ((AppSpecificAuthToken.expiration > datetime.now()) | (AppSpecificAuthToken.expiration >> None)))
if (owner is not None):
query = query.where((AppSpecificAuthTok... |
def filter(example, uniques, args):
if (not check_uniques(example, uniques)):
return False
elif example['autogenerated']:
return False
elif (example['line_max'] > args.line_max):
return False
elif (example['line_mean'] > args.line_mean):
return False
elif (example['al... |
def collate_fn_obj(batch):
(name_list, instance2mask_list, obj_point_list, obj_label_list) = ([], [], [], [])
for i in batch:
name_list.append(i[0])
instance2mask_list.append(i[1])
obj_point_list.append(i[2])
obj_label_list.append(i[4])
return (name_list, instance2mask_list, ... |
def main(dir_name, runs: Optional[List], first_n_cases=None, get_uncompressed=False, abs_path=False):
summaries = []
uncompressed = []
with open((((RESULTS_DIR / dir_name) / runs[0]) / 'params.json'), 'r') as f:
params = json.load(f)
print(params)
for run_dir in ((RESULTS_DIR / dir_name)... |
()
def intercepted_build_args(monkeypatch):
intercepted = ArgsInterceptor()
monkeypatch.setattr(linux, 'build', intercepted)
monkeypatch.setattr(macos, 'build', intercepted)
monkeypatch.setattr(windows, 'build', intercepted)
(yield intercepted)
assert (intercepted.call_count <= 1) |
def get_transformed_webhook_payload(bb_payload, default_branch=None):
try:
validate(bb_payload, BITBUCKET_WEBHOOK_PAYLOAD_SCHEMA)
except Exception as exc:
logger.exception('Exception when validating Bitbucket webhook payload: %s from %s', exc.message, bb_payload)
raise InvalidPayloadExce... |
def action_alias(actions, medicine_alias):
triple = ['intent', 'slot', 'value1', 'value2']
res = ''
for action in actions:
if (('slot' in action.keys()) and (action['slot'] == 'medicine') and ('value1' in action.keys()) and ((action['value1'] + '.txt') in entity)):
medicine = json.load(o... |
class QCECPPotential(_QCBase):
ecp_type: str
angular_momentum: Sequence[int]
r_exponents: Sequence[int]
gaussian_exponents: Sequence[(float | str)]
coefficients: Sequence[Sequence[(float | str)]]
def to_hdf5(self, group: h5py.Group) -> None:
group.attrs['angular_momentum'] = self.angular... |
def InceptionV3(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000):
if (weights not in {'imagenet', None}):
raise ValueError('The `weights` argument should be either `None` (random initialization) or `imagenet` (pre-training on ImageNet).')
if ((weight... |
def main():
global best_loss
loss_history_train = []
loss_history_val = []
data_dir = args.data_dir
img_dir_train = os.path.join(data_dir, 'img/train')
img_dir_val = os.path.join(data_dir, 'img/test')
txt_file_train = os.path.join(data_dir, 'annot_train.txt')
txt_file_val = os.path.join(... |
def parse(opt_path, is_train=True):
with open(opt_path, mode='r') as f:
(Loader, _) = ordered_yaml()
opt = yaml.load(f, Loader=Loader)
opt['is_train'] = is_train
for (phase, dataset) in opt['datasets'].items():
phase = phase.split('_')[0]
dataset['phase'] = phase
if (... |
class OnChangeHookApp(cmd2.Cmd):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.add_settable(utils.Settable('quiet', bool, 'my description', self, onchange_cb=self._onchange_quiet))
def _onchange_quiet(self, name, old, new) -> None:
self.poutput(('You changed... |
def torch_nn_conv2d(self, input):
(h_in, w_in) = input.shape[(- 2):]
shape = None
padding = self.padding
if (padding == 'valid'):
padding = (0, 0)
if (padding == 'same'):
shape = list(input.shape)
if (shape is None):
shape = list(input.shape)
h_out = math.floor(((... |
class nnUNetTrainerNoDA(nnUNetTrainer):
def get_training_transforms(patch_size: Union[(np.ndarray, Tuple[int])], rotation_for_DA: dict, deep_supervision_scales: Union[(List, Tuple)], mirror_axes: Tuple[(int, ...)], do_dummy_2d_data_aug: bool, order_resampling_data: int=1, order_resampling_seg: int=0, border_val_seg... |
class Migration(migrations.Migration):
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('submissions', '0009_auto__2103')]
operations = [migrations.CreateModel(name='SubmissionComment', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name=... |
def test_while_with_if_else() -> None:
src = '\n while n > 10:\n if n > 20:\n print(y)\n else:\n print(j)\n else:\n print(x)\n '
cfg = build_cfg(src)
expected_blocks = [['n > 10'], ['n > 20'], ['print(y)'], ['print(j)'], ['print(x)'], []]
assert (expec... |
def metadata_path_constructor(loader, node) -> MetadataInfo:
raw = loader.construct_scalar(node)
if (':' in raw):
(artifact_uuids, rel_fp) = raw.split(':')
artifact_uuids = artifact_uuids.split(',')
else:
artifact_uuids = []
rel_fp = raw
action_fp = Path(loader.name)
... |
class Grayscale(object):
def __init__(self, num_output_channels=1):
self.num_output_channels = num_output_channels
def __call__(self, img):
return F.to_grayscale(img, num_output_channels=self.num_output_channels)
def __repr__(self):
return (self.__class__.__name__ + '(num_output_chan... |
def process_rule_smiles_tables(c, filenames, reporter):
start_time = time.time()
reporter.report('[Stage 2/7] Merging rule_smiles tables ...')
create_rule_smiles_table(c)
for (db_id, progress_str, filename) in enumerate_progress(filenames):
with transaction(c):
create_rule_smiles_map... |
def test_overriding_generated_unstructure_hook_func():
converter = Converter()
class Inner():
a: int
class Outer():
i: Inner
inst = Outer(Inner(1))
converter.unstructure(inst)
converter.register_unstructure_hook_func((lambda t: (t is Inner)), (lambda _: {'a': 2}))
r = convert... |
def serialize_df(table_data: pd.DataFrame, table_name: str, table_path: str, serialize_method: str='tsv', num_visible_rows: int=3, max_tokens: int=1000, data_dir_splitter: str='backend/data/') -> str:
if (serialize_method == 'tsv'):
pretty_path = '/'.join(table_path.split(data_dir_splitter)[(- 1)].strip('/'... |
class AltCLIPTextConfig(PretrainedConfig):
model_type = 'altclip_text_model'
def __init__(self, vocab_size=250002, hidden_size=1024, num_hidden_layers=24, num_attention_heads=16, intermediate_size=4096, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=514, ty... |
.parametrize('uri', [rfc3986.uri_reference('//google.com'), rfc3986.uri_reference('//google.com?query=value'), rfc3986.uri_reference('//google.com#fragment')])
def test_multiple_missing_components(uri):
validator = validators.Validator().require_presence_of('scheme', 'path')
with pytest.raises(exceptions.Missin... |
class MultiVectorType(types.Type):
def __init__(self, layout: LayoutType, dtype: types.DType):
self.layout_type = layout
self.value_type = dtype
super().__init__(name='MultiVector({!r}, {!r})'.format(self.layout_type, self.value_type))
def key(self):
return (self.layout_type, sel... |
class TweetyNet(nn.Module):
def __init__(self, num_classes, input_shape=(1, 513, 88), padding='SAME', conv1_filters=32, conv1_kernel_size=(5, 5), conv2_filters=64, conv2_kernel_size=(5, 5), pool1_size=(8, 1), pool1_stride=(8, 1), pool2_size=(8, 1), pool2_stride=(8, 1), hidden_size=None, rnn_dropout=0.0, num_layers=... |
class TensorNetwork():
def __init__(self, network_id, instance, fm, node_count, num_stage=(- 1), num_row=(- 1), num_hyperedge=(- 1), staged_nodes=None):
self.network_id = network_id
self.inst = instance
self.fm = fm
self.gnp = fm.gnp
self.nodeid2labelid = {}
self.num_... |
def test_decode_processed_column():
assert (du.decode_processed_column(f'0___{du.ColDataType.NUMERIC}___float_00') == 'float_00')
assert (du.decode_processed_column(f'0___{du.ColDataType.NUMERIC}___int_01') == 'int_01')
assert (du.decode_processed_column(f'0___{du.ColDataType.DATETIME}___datetime_03') == 'd... |
class BlockDevice(Module):
def _data(self):
raise NotImplementedError
def __init__(self, device):
self.device = device
super().__init__()
def is_partition(self):
return (self._data['start_sector'] > 0)
def size(self):
return self._data['size']
def sector_size(... |
def setup(app):
if (sphinx.version_info >= (1, 6, 0)):
app.add_html_theme('sphinx_rtd_theme', path.abspath(path.dirname(__file__)))
if (sphinx.version_info >= (1, 8, 0)):
rtd_locale_path = path.join(path.abspath(path.dirname(__file__)), 'locale')
app.add_message_catalog('sphinx', rtd_loc... |
def reduce_scalar_outputs(scalar_outputs):
world_size = get_world_size()
if (world_size < 2):
return scalar_outputs
with torch.no_grad():
names = []
scalars = []
for k in sorted(scalar_outputs.keys()):
names.append(k)
if isinstance(scalar_outputs[k], t... |
def set_tcs_debug_flag(tcs_addr):
string = read_from_memory((tcs_addr + 8), 4)
if (string is None):
return False
flag = struct.unpack('I', string)[0]
flag |= 1
process = lldb.debugger.GetSelectedTarget().GetProcess()
pid = process.GetProcessID()
fd = os.open((('/proc/' + str(pid)) + ... |
def _qubit_operator():
pauli_list = PauliList(['IIIIIIIIIII', 'IIIIIIIZZZY', 'IIIIIIIZZZZ', 'IIIIIIXIXII', 'IIIIIXZIZXI', 'IIIIZYIZIYI', 'IIIIZZYZYZI', 'IIIIZZZIIIY', 'IIIIZZZIIIZ', 'IIIIZZZZZZI', 'IIIXIIZXZIZ', 'IIIXXZIZIZZ', 'IIXZIZIXIZZ', 'IIXZXIZZZIZ', 'IIYIYIZIZIZ', 'IIYIZZIYIZZ', 'IIZYYZIIIZZ', 'IIZYZIZYZIZ',... |
def get_dataset(data_config):
train_dataset = Registers.datasets[data_config.dataset_type](data_config.dataset_config, stage='train')
val_dataset = Registers.datasets[data_config.dataset_type](data_config.dataset_config, stage='val')
test_dataset = Registers.datasets[data_config.dataset_type](data_config.da... |
def name(url, safe_name=True):
url = format.url(url)
up = urllib.parse.urlparse(url)
name = up.path.split('/')[(- 1)]
if (not name):
name = up.query.split('=', 1)[::(- 1)][0].split('&', 1)[0]
if ((not name) and up.fragment):
name = ('#' + up.fragment)
elif (name and up.fragment):... |
class AttributeAdminForm(forms.ModelForm):
key = forms.SlugField(required=True)
class Meta():
model = Attribute
fields = ['uri', 'uri_prefix', 'key', 'path', 'comment', 'locked', 'editors', 'parent']
def clean(self):
AttributeUniqueURIValidator(self.instance)(self.cleaned_data)
... |
def _create_fake_file_handler(in_fname, filename_info=None, filetype_info=None, fh_kwargs=None):
if (filename_info is None):
filename_info = {'segment': 8, 'total_segments': 10}
if (filetype_info is None):
filetype_info = {'file_type': 'hsd_b01'}
if (fh_kwargs is None):
fh_kwargs = {... |
def calculate_quantsim_accuracy(model: torch.nn.Module, evaluator: aimet_common.defs.EvalFunction, use_cuda: bool=False) -> float:
input_shape = (1, image_net_config.dataset['image_channels'], image_net_config.dataset['image_width'], image_net_config.dataset['image_height'])
if use_cuda:
dummy_input = t... |
def export_pinnacle(pinnacle_subparsers):
parser = pinnacle_subparsers.add_parser('export', help='Export a raw file to DICOM')
parser.add_argument('input_path', type=str, help="Root Patient directory of raw Pinnacle data (directory containing the 'Patient' file). Alternatively a TAR archive can be supplied.")
... |
def detect_missing_data(multi_ds, user_impute_strategy=cfg.default_imputation_strategy):
missing_data_flag = dict()
for (ds_id, data_mat) in multi_ds:
is_nan = np.isnan(data_mat)
if is_nan.any():
data_missing_here = True
num_sub_with_md = np.sum((is_nan.sum(axis=1) > 0))
... |
def minimum_time_steps(error_budget: float, alg: AlgorithmSummary, rotation_model: RotationCostModel) -> int:
c_min = math.ceil((((alg.measurements + alg.rotation_gates) + alg.t_gates) + (3 * alg.toffoli_gates)))
eps_syn = (error_budget / 3)
c_min += math.ceil((alg.rotation_circuit_depth * rotation_model.ro... |
def disable_abusing_user(username, queue_name):
if (not username):
raise Exception('Must enter a username')
user = ask_disable_namespace(username, queue_name)
if user.organization:
members = model.organization.get_organization_member_set(user)
for membername in members:
a... |
def test_bwlimit():
with expected_protocol(TeledyneMAUI, [(b'CHDR OFF', None), (b'BWL C1,OFF', None), (b'BWL?', b'C1,OFF'), (b'BWL C1,200MHZ', None), (b'BWL?', b'C1,200MHZ'), (b'BWL C1,ON', None), (b'BWL?', b'C1,ON')]) as instr:
instr.ch_1.bwlimit = 'OFF'
assert (instr.bwlimit['C1'] == 'OFF')
... |
class MbConvBlock(nn.Module):
def __init__(self, in_chs: int, out_chs: int, stride: int=1, dilation: Tuple[(int, int)]=(1, 1), cfg: MaxxVitConvCfg=MaxxVitConvCfg(), drop_path: float=0.0):
super(MbConvBlock, self).__init__()
norm_act_layer = partial(get_norm_act_layer(cfg.norm_layer, cfg.act_layer), ... |
def test_cmd_list_input_with_complex_args_error_on_first():
cmd1 = get_cmd('tests/testfiles/cmds/args.sh', 'tests\\testfiles\\cmds\\args.bat')
cmd2 = get_cmd('tests/testfiles/cmds/args2.sh', 'tests\\testfiles\\cmds\\args2.bat')
context = Context({'a': 'WRONG', 'b': 'two two', 'c': 'three', 'd': cmd1, 'e': c... |
class TopSource(FSSource):
is_inheritable = False
def __init__(self, encoding='utf-8'):
super(TopSource, self).__init__('.', encoding)
def _resolve_path(self, path_in_source):
return path_in_source
def get(self, path_in_source):
if (path_in_source == '-'):
lines = sys... |
def MLP(channels, num_points=None, channel_last=True, bias=False):
if channel_last:
return nn.Sequential(*[nn.Sequential(nn.Linear(channels[(i - 1)], channels[i], bias=bias), GraphBatchNorm1d(channels[i], num_points), nn.LeakyReLU(negative_slope=0.2)) for i in range(1, len(channels))])
return nn.Sequent... |
def pair_within_simultaneously(labels: list) -> tuple:
if (len(labels) <= 3):
return
for partition in _gen_partitions(labels):
generator_list = [_loop_iterator(pair_within, partition[j]) for j in range(len(partition))]
for dummy1 in range(((len(partition[(- 2)]) - 1) + (len(partition[(- ... |
.skipif((not HAVE_DEPS_FOR_RESOURCE_ESTIMATES), reason='pyscf and/or jax not installed.')
def test_compute_cost():
nRe = 108
lam_re = 2135.3
dRe = 705831
dE = 0.001
chi = 10
nLi = 152
lam_Li = 1547.3
dLi = 440501
dE = 0.001
chi = 10
Nkx = 2
Nky = 2
Nkz = 2
res = _... |
def compare_states(test_fixture, state_1, state_2, check_heads=True):
compare_model_state(test_fixture, state_1['base_model'], state_2['base_model'], check_heads)
test_fixture.assertEqual(len(state_1['losses']), len(state_2['losses']))
for (loss_1, loss_2) in zip(state_1['losses'], state_2['losses']):
... |
class DistributedMinerWrapper(torch.nn.Module):
def __init__(self, miner):
super().__init__()
self.miner = miner
def forward(self, embeddings, labels, ref_emb=None, ref_labels=None):
(embeddings, labels) = all_gather_embeddings_labels(embeddings, labels)
if (ref_emb is not None):... |
class LaplacianBlender(nn.Module):
def __init__(self, levels=5, gaussian_kernel_size=45, gaussian_sigma=1, level_size_adder=0, level_sigma_multiplier=2):
super().__init__()
assert ((gaussian_kernel_size % 2) == 1), 'gaussian_kernel_size needs to be odd for easier padding'
assert ((level_size... |
_kernel_api(params={'ctlref': POINTER})
def hook__ctl_deregister(ql, address, params):
userctl = kern_ctl_reg_t(ql, params['userctl'])
userctl = userctl.loadFromMem()
ctl_name = ql.mem.string(params['userctl']).encode()
ql.log.debug(('A ctl event has been deregistered: %s' % ctl_name))
ql.os.ev_mana... |
def eval_exec_match(db: str, p_str: str, g_str: str, plug_value: bool, keep_distinct: bool, progress_bar_for_each_datapoint: bool) -> int:
(p_str, g_str) = (postprocess(p_str), postprocess(g_str))
if (not keep_distinct):
p_str = remove_distinct(p_str)
g_str = remove_distinct(g_str)
order_mat... |
def resizeWindow(win, w, h, timeout=2.0):
QtWidgets.QApplication.processEvents()
QtTest.QTest.qWaitForWindowExposed(win)
win.resize(w, h)
start = time.time()
while True:
(w1, h1) = (win.width(), win.height())
if ((w, h) == (w1, h1)):
return
QtTest.QTest.qWait(10)
... |
def get_venv_summary(venv_dir: Path, *, package_name: Optional[str]=None, new_install: bool=False, include_injected: bool=False) -> Tuple[(str, VenvProblems)]:
venv = Venv(venv_dir)
if (package_name is None):
package_name = venv.main_package_name
(venv_problems, warning_message) = venv_health_check(... |
class TestOrganizationApplications(ApiTestCase):
def test_list_create_applications(self):
self.login(ADMIN_ACCESS_USER)
json = self.getJsonResponse(OrganizationApplications, params=dict(orgname=ORGANIZATION))
self.assertEqual(2, len(json['applications']))
found = False
for ap... |
def build_resnet(repetitions=(2, 2, 2, 2), include_top=True, input_tensor=None, input_shape=None, classes=1000, block_type='usual'):
input_shape = _obtain_input_shape(input_shape, default_size=224, min_size=96, data_format='channels_last', require_flatten=include_top)
if (input_tensor is None):
img_inpu... |
def define_P(in_size=512, out_size=512, min_feat_size=32, relu_type='LeakyReLU', isTrain=False, weight_path=None):
net = ParseNet(in_size, out_size, min_feat_size, 64, 19, norm_type='bn', relu_type=relu_type, ch_range=[32, 256])
if (not isTrain):
net.eval()
if (weight_path is not None):
net.... |
def build_dataset(args, rank=0):
tok = get_tokenizer(args)
feat_db = ImageFeaturesDB(args.img_ft_file, args.image_feat_size)
obj_db = ObjectFeatureDB(args.obj_ft_file, args.obj_feat_size)
obj2vps = load_obj2vps(os.path.join(args.anno_dir, 'BBoxes.json'))
dataset_class = ReverieObjectNavBatch
if ... |
def inject_trainable_lora_extended(model: nn.Module, target_replace_module: Set[str]=UNET_EXTENDED_TARGET_REPLACE, r: int=4, loras=None):
require_grad_params = []
names = []
if (loras != None):
loras = torch.load(loras)
for (_module, name, _child_module) in _find_modules(model, target_replace_mo... |
def validate_instance(instance, element, *validators):
exception_message = None
try:
instance.full_clean()
for validator in validators:
validator((instance if instance.id else None))(vars(instance))
except ValidationError as e:
try:
exception_message = '; '.jo... |
class _Strip():
__slots__ = ('x', 'y', 'max_height', 'y2')
def __init__(self, y: int, max_height: int) -> None:
self.x = 0
self.y = y
self.max_height = max_height
self.y2 = y
def add(self, width: int, height: int) -> Tuple[(int, int)]:
assert ((width > 0) and (height ... |
def run_cmd(app, cmd):
saved_sysout = sys.stdout
sys.stdout = app.stdout
copy_cmd_stdout = StdSim(app.stdout)
copy_stderr = StdSim(sys.stderr)
try:
app.stdout = copy_cmd_stdout
with redirect_stdout(copy_cmd_stdout):
with redirect_stderr(copy_stderr):
app.o... |
class TestCallback(aiotest.TestCase):
.trio
async def test_call_soon(self, loop):
result = []
def hello_world(loop):
result.append('Hello World')
loop.stop()
loop.call_soon(hello_world, loop)
(await loop.stop().wait())
assert (result == ['Hello Wor... |
def _reorder_multi_input_op_products(op: Op):
if (op.type in ['Add', 'AddN', 'ConcatV2', 'Merge', 'Mul']):
old_products = op.get_input_products()
tf_op_input_list = list(op.get_module().inputs)
new_product_list = ([None] * len(tf_op_input_list))
for product in old_products:
... |
def resnet_v2_200(inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, reuse=None, scope='resnet_v2_200'):
blocks = [resnet_utils.Block('block1', bottleneck, (([(256, 64, 1)] * 2) + [(256, 64, 2)])), resnet_utils.Block('block2', bottleneck, (([(512, 128, 1)] * 23) + [(512, 128, 2)])), r... |
class GridSpectralModel(gpytorch.models.ExactGP):
def __init__(self, train_x, train_y, likelihood, omega=None, mean=gpytorch.means.ConstantMean, normalize=False, **kwargs):
super(GridSpectralModel, self).__init__(train_x, train_y, likelihood)
self.mean_module = mean()
self.covar_module = Spe... |
class TestSelectFilter(unittest.TestCase):
(ONE_TEST_TIMEOUT)
def test_select_column_filter_value(self):
(rdf_graph, schema) = get_graph_and_schema('dev', 'concert_singer')
correct_sparql_query = textwrap.dedent(' SELECT ?Name\n WHERE\n {\n ?singer a... |
.parametrize('transformer', [partial(Transformer.from_pipeline, '+proj=pipeline +ellps=GRS80 +step +proj=cart'), partial(Transformer.from_crs, 4326, 3857), partial(Transformer.from_proj, 4326, 3857)])
('os.environ', {'PROJ_NETWORK': 'OFF'}, clear=True)
def test_network__enable(transformer):
with proj_network_env():... |
class VoltageModel(pybamm.BaseSubModel):
def __init__(self, param, options=None):
super().__init__(param)
self.model_options = options
def get_coupled_variables(self, variables):
ocv = variables['Open-circuit voltage [V]']
number_of_rc_elements = self.model_options['number of rc ... |
.skipif((not IS_LINUX), reason='Irrelevant on non-linux')
class TestSpecialRelease(DistroTestCase):
def _test_outcome(self, outcome: Dict[(str, str)]) -> None:
assert (self.distro.id() == outcome.get('id', ''))
assert (self.distro.name() == outcome.get('name', ''))
assert (self.distro.name(p... |
class FromToLineNoTest(unittest.TestCase):
def setUp(self) -> None:
self.astroid = resources.build_file('data/format.py')
def test_callfunc_lineno(self) -> None:
stmts = self.astroid.body
discard = stmts[0]
self.assertIsInstance(discard, nodes.Expr)
self.assertEqual(disca... |
.parametrize('has_memo_data', [False, True])
def test_create_pickup_list_random_data_source(has_memo_data: bool, empty_patches, generic_pickup_category, default_generator_params):
rng = Random(5000)
resource_b = ItemResourceInfo(0, 'B', 'B', 10)
model_1 = MagicMock(spec=PickupModel)
model_1.game = Rando... |
class FP3232(rq.ValueField):
structcode = 'lL'
structvalues = 2
def check_value(self, value):
return value
def parse_value(self, value, display):
(integral, frac) = value
ret = float(integral)
ret += (float(frac) * (1.0 / (1 << 32)))
return ret |
class ScopedHandle(asyncio.Handle):
__slots__ = ('_scope',)
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self._scope = trio.CancelScope()
def cancel(self):
super().cancel()
self._scope.cancel()
def _repr_info(self):
return (super()._repr_info() +... |
class Tokenizer():
def __init__(self, config, headers):
self.model_input_names = ['image_path', 'input_pixels']
self.padding_side = 'right'
self.ann_path = config.annotation_file
self.threshold = config.threshold
self.dataset = config.dataset
if (self.dataset == 'iu_x... |
class COCOEvalCap(object):
def __init__(self, splits, tok, val_instr_data, use_clip16=False):
self.evalImgs = []
self.eval = {}
self.splits = splits
self.tok = tok
self.gt = defaultdict(list)
self.use_clip16 = use_clip16
for split in splits:
for it... |
class PublisherKeywordReportView(PublisherAccessMixin, BaseReportView):
template_name = 'adserver/reports/publisher-keyword.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
publisher_slug = kwargs.get('publisher_slug', '')
publisher = get_object_or... |
def test_phase_version_update(tester: CommandTester) -> None:
assert isinstance(tester.command, VersionCommand)
tester.command.poetry.package._set_version('1.2.4a0')
tester.execute('prerelease --next-phase')
assert (tester.io.fetch_output() == 'Bumping version from 1.2.4a0 to 1.2.4b0\n') |
def gen_value_test():
return [gen_rimm_value_test('addi', 0, 0, 0), gen_rimm_value_test('addi', 1, 1, 2), gen_rimm_value_test('addi', 3, 7, 10), gen_rimm_value_test('addi', 4, 4095, 3), gen_rimm_value_test('addi', 0, 2048, ), gen_rimm_value_test('addi', , 0, ), gen_rimm_value_test('addi', , 2048, ), gen_rimm_value_... |
class TestUserSubscription(ApiTestCase):
def getSubscription(self):
return self.getJsonResponse(UserPlan)
def test_updateplan(self):
self.login(ADMIN_ACCESS_USER)
self.putJsonResponse(UserPlan, data=dict(plan='free'))
sub = self.getSubscription()
self.assertEqual('free', ... |
('PyQt6.QtWidgets.QGraphicsView.mousePressEvent')
def test_mouse_press_when_move_window_active(mouse_event_mock, qapp):
parent = QtWidgets.QMainWindow()
view = BeeGraphicsView(qapp, parent)
overlay = WelcomeOverlay(view)
overlay.movewin_active = True
overlay.mousePressEvent(MagicMock())
assert (... |
class TestTestSet(unittest.TestCase):
def setUp(self):
self.test_set = CustomTestSet()
def test_skip_solver_issue(self):
foo = custom_problem(name='foo')
self.test_set.known_solver_issues.add(('foo', 'bar'))
self.assertTrue(self.test_set.skip_solver_issue(foo, 'bar'))
sel... |
class FluentdCollector(diamond.collector.Collector):
API_PATH = '/api/plugins.json'
def get_default_config_help(self):
config_help = super(FluentdCollector, self).get_default_config_help()
config_help.update({'host': 'Fluentd host', 'port': 'Fluentd port', 'collect': 'Plugins and their metrics t... |
class KazooBarrierTests(KazooTestCase):
def test_barrier_not_exist(self):
b = self.client.Barrier('/some/path')
assert b.wait()
def test_barrier_exists(self):
b = self.client.Barrier('/some/path')
b.create()
assert (not b.wait(0))
b.remove()
assert b.wait(... |
class BertConverter(Converter):
def converted(self) -> Tokenizer:
vocab = self.original_tokenizer.vocab
tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(self.original_tokenizer.unk_token)))
tokenize_chinese_chars = False
strip_accents = False
do_lower_case = False
... |
class SegToImageTransforms(TransformsConfig):
def __init__(self, opts):
super(SegToImageTransforms, self).__init__(opts)
def get_transforms(self):
transforms_dict = {'transform_gt_train': transforms.Compose([transforms.Resize((320, 320)), transforms.ToTensor(), transforms.Normalize([0.5, 0.5, 0.... |
def my_net(modelname):
if (modelname == 'imagenet_ResUnet'):
if default_config['Pretrain']:
print('Using pretrain model')
model = smp.Unet(encoder_name='resnet18', encoder_weights='imagenet', in_channels=1, classes=4)
else:
model = smp.Unet(encoder_name='resnet18'... |
class WebclientTest(EvenniaWebTest):
url_name = 'webclient:index'
_settings(WEBCLIENT_ENABLED=True)
def test_get(self):
self.authenticated_response = 200
self.unauthenticated_response = 200
super(WebclientTest, self).test_get()
_settings(WEBCLIENT_ENABLED=False)
def test_get_... |
def upgrade(op, tables, tester):
op.create_table('userpromptkind', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=255), nullable=False), sa.PrimaryKeyConstraint('id', name=op.f('pk_userpromptkind')))
op.create_index('userpromptkind_name', 'userpromptkind', ['name'], unique=Fal... |
class PanopticReconstructionQuality(Metric):
def __init__(self, matching_threshold=0.25, category_information=None, ignore_labels=None, reduction='mean'):
super().__init__()
if (ignore_labels is None):
ignore_labels = [0, 12]
self.ignore_labels = ignore_labels
self.matchi... |
def parse_args():
parser = argparse.ArgumentParser(description='Generate training and val set of ILST ')
parser.add_argument('root_path', help='Root dir path of ILST')
parser.add_argument('--val-ratio', help='Split ratio for val set', default=0.0, type=float)
parser.add_argument('--nproc', default=1, ty... |
.parametrize('username,password', users)
.parametrize('export_format', export_formats)
def test_detail_export(db, client, username, password, export_format):
client.login(username=username, password=password)
instance = Attribute.objects.first()
url = ((reverse(urlnames['detail_export'], args=[instance.pk])... |
class TestClass():
def test_class_with_init_warning(self, pytester: Pytester) -> None:
pytester.makepyfile('\n class TestClass1(object):\n def __init__(self):\n pass\n ')
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*cannot c... |
class JtopServer(Process):
def __init__(self, force=False):
self.force = force
if (os.getuid() != 0):
raise JtopException('jtop service need sudo to work')
self._version = deepcopy(get_var(VERSION_RE))
logger.info('jetson_stats {version} - server loaded'.format(version=se... |
def main() -> None:
torch.random.manual_seed(42)
model = Model()
optim = torch.optim.Adagrad(model.parameters(), lr=0.001)
train_dataloader = prepare_dataloader()
loss_fn = torch.nn.CrossEntropyLoss()
metric = MulticlassAccuracy()
compute_frequency = 4
num_epochs_completed = 0
while ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.