code stringlengths 281 23.7M |
|---|
.end_to_end()
def test_collect_string_product_raises_error_with_annotation(runner, tmp_path):
source = '\n from pytask import Product\n from typing_extensions import Annotated\n\n def task_write_text(out: Annotated[str, Product] = "out.txt") -> None:\n out.touch()\n '
tmp_path.joinpath('task_... |
def test_inp_tags_getter_and_setter():
common_data = {'ElementType': (['Subcatch'] * 4), 'Name': ['CA-1', 'CA-7', 'CA-8', 'CA-11'], 'Tag': (['CA'] * 4)}
expected_output = pd.DataFrame(common_data)
expected_output.set_index(['ElementType'], inplace=True)
common_data['Tag'] = (['Modified'] * 4)
tags_t... |
def save_h5_output(h5_filename, seg, segrefine, group, grouppred, label_dtype='uint8'):
print(h5_filename)
h5_fout = h5py.File(h5_filename)
h5_fout.create_dataset('seglabel', data=seg, compression='gzip', compression_opts=1, dtype=label_dtype)
h5_fout.create_dataset('segrefine', data=segrefine, compress... |
def hsic_gam(X=None, Y=None, alph=None, width_x=None, width_y=None, K=None, Kc=None, L=None, Lc=None, mode=None, kwdth='mdbs'):
n = X.shape[0]
if (kwdth == 'scott'):
width_x = bw_scott(X)
width_y = bw_scott(Y)
elif (kwdth == 'silverman'):
width_x = bw_silverman(X)
width_y = b... |
class GeodesicLengthSpace(LengthSpace):
def geodesic(self, pt_a: Point, pt_b: Point, frac: float=0.5, **kwargs) -> Point:
if (len(kwargs) > 0):
warnings.warn(f'{self.__class__.__name__}.geodesic takes no kwargs, but got {kwargs.keys()}')
if torch.allclose(pt_a, pt_b):
return ... |
def get_imagenet_dataloader_sample(data_folder, args, is_sample=True):
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
train_transform = transforms.Compose([transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), normalize])
test_t... |
def basic_blocks(dim, index, layers, segment_dim, mlp_ratio=3.0, qkv_bias=False, qk_scale=None, attn_drop=0, drop_path_rate=0.0, skip_lam=1.0, mlp_fn=WeightedPermuteMLP, **kwargs):
blocks = []
for block_idx in range(layers[index]):
block_dpr = ((drop_path_rate * (block_idx + sum(layers[:index]))) / (sum... |
.parametrize('remote_config, expected_token', [({'type': HvcsClient.GITHUB.value}, EnvConfigVar(env='GH_TOKEN')), ({'type': HvcsClient.GITLAB.value}, EnvConfigVar(env='GITLAB_TOKEN')), ({'type': HvcsClient.GITEA.value}, EnvConfigVar(env='GITEA_TOKEN')), ({}, EnvConfigVar(env='GH_TOKEN'))])
def test_load_hvcs_default_to... |
class DeletedMessagesLogURLTests(AuthenticatedAPITestCase):
def setUpTestData(cls):
cls.author = cls.actor = User.objects.create(id=324888, name='Black Knight', discriminator=1975)
cls.deletion_context = MessageDeletionContext.objects.create(actor=cls.actor, creation=datetime.now(tz=UTC))
def te... |
class DataLoaderTrain(IterableDataset):
def __init__(self, data_dir, filename_pat, args, world_size, worker_rank, cuda_device_idx, news_index, news_combined, word_dict, enable_prefetch=True, enable_shuffle=False, enable_gpu=True):
self.data_dir = data_dir
self.filename_pat = filename_pat
sel... |
class DuringEvent(Event):
def _trigger(self, model, *args, **kwargs):
res = super(DuringEvent, self)._trigger(model, *args, **kwargs)
if (res is False):
state = self.machine.get_state(model.state)
event_data = EventData(state, self, self.machine, model, args=args, kwargs=kwar... |
class WorkGroup(ContentManageable, NameSlugModel):
active = models.BooleanField(default=True, db_index=True)
approved = models.BooleanField(default=False, db_index=True)
short_description = models.TextField(blank=True, help_text='Short description used on listing pages')
purpose = MarkupField(default_ma... |
class _SavedCmd2Env():
def __init__(self) -> None:
self.readline_settings = _SavedReadlineSettings()
self.readline_module: Optional[ModuleType] = None
self.history: List[str] = []
self.sys_stdout: Optional[TextIO] = None
self.sys_stdin: Optional[TextIO] = None |
class SetEmojiStatus():
async def set_emoji_status(self: 'pyrogram.Client', emoji_status: Optional['types.EmojiStatus']=None) -> bool:
(await self.invoke(raw.functions.account.UpdateEmojiStatus(emoji_status=(emoji_status.write() if emoji_status else raw.types.EmojiStatusEmpty()))))
return True |
class PresetEchoesBeamConfiguration(PresetTab, Ui_PresetEchoesBeamConfiguration):
def __init__(self, editor: PresetEditor, game_description: GameDescription, window_manager: WindowManager):
super().__init__(editor, game_description, window_manager)
self.setupUi(self)
def _add_header(text: st... |
class WrappedChecksumCL(Component):
def construct(s, DutType=ChecksumCL):
s.recv = CalleeIfcCL(Type=Bits128)
s.give = CalleeIfcCL(Type=Bits32)
s.checksum_unit = DutType()
s.out_q = BypassQueueCL(num_entries=1)
connect_pairs(s.recv, s.checksum_unit.recv, s.checksum_unit.send, ... |
def _fill_flatten_shape_if_needed(op: Op):
if ((op.type == 'Flatten') and op.output_shape):
dims = op.output_shape.as_list()
if dims:
if (dims[(- 1)] is None):
output_size = 1
input_shape = op.inputs[0].shape.as_list()
for dim in input_shap... |
def test_v1_event_payment_sent_failed_schema():
event = EventPaymentSentFailed(token_network_registry_address=UNIT_TOKEN_NETWORK_REGISTRY_ADDRESS, token_network_address=UNIT_TOKEN_NETWORK_ADDRESS, identifier=PaymentID(1), target=TargetAddress(factories.make_address()), reason='whatever')
log_time = datetime.dat... |
(cc=STDCALL, params={'pSecDesc': PSECURITY_DESCRIPTOR, 'cAuthSvc': LONG, 'asAuthSvc': POINTER, 'pReserved1': PVOID, 'dwAuthnLevel': DWORD, 'dwImpLevel': DWORD, 'pAuthList': PVOID, 'dwCapabilities': DWORD, 'pReserved3': PVOID})
def hook_CoInitializeSecurity(ql: Qiling, address: int, params):
return S_OK |
class ESRI_ArcGIS(WMSBase):
layer_prefix = 'ESRI'
name = 'ESRI_ArcGIS'
def __init__(self, m=None):
self.m = m
self.m.add_wms.ESRI_ArcGIS
self.wmslayers = []
for servicename in self.m.add_wms.ESRI_ArcGIS._layers:
self.wmslayers.extend([((servicename + '__') + key) ... |
def setup_regularizer(opt):
try:
reg_name = opt.get('regularizer')
except Exception:
print('Please specify the regularizer type')
assert (reg_name in ['fixed', 'alter_mf']), NotImplementedError('Invalid {} regularizer'.format(reg_name))
if (reg_name == 'fixed'):
regularizer = Fix... |
def _clean_text(text):
plm_special_tokens = '(\\<pad\\>)|(\\<s\\>)|(\\<\\/s\\>)|(\\<unk\\>)|(\\<\\|endoftext\\|\\>)'
text = re.sub(plm_special_tokens, '', text)
moses_norm = MosesPunctNormalizer()
text = moses_norm.normalize(text)
text = _tokenization_norm(text)
text = clean(text, fix_unicode=Tr... |
def test_auto_fp16():
with pytest.raises(TypeError):
class ExampleObject(object):
_fp16()
def __call__(self, x):
return x
model = ExampleObject()
input_x = torch.ones(1, dtype=torch.float32)
model(input_x)
class ExampleModule(nn.Module):
... |
def test_default_changelog_template(repo_with_git_flow_and_release_channels_angular_commits, default_angular_parser):
version = Version.parse('1.1.0-alpha.3')
repo = repo_with_git_flow_and_release_channels_angular_commits
env = environment(trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True)
... |
class Delivery(Object):
def __init__(self, payload=None, log=None, errors=None, error=None):
if (payload is None):
payload = []
if (log is None):
log = []
if (errors is None):
errors = []
if (error is not None):
errors.append(error)
... |
def test_remote_pipe_closed():
master_pid = os.getpid()
with pm.Model():
x = pm.Normal('x', shape=2, mu=0.1)
at_pid = pt.as_tensor_variable(np.array(master_pid, dtype='int32'))
pm.Normal('y', mu=_crash_remote_process(x, at_pid), shape=2)
step = pm.Metropolis()
with pytest... |
class LocaldriveTests(MusicTest):
def setUp(self) -> None:
super().setUp()
self._setup_test_library()
def test_suggested_song(self) -> None:
suggestion = json.loads(self.client.get(reverse('offline-suggestions'), {'term': 'backbeat', 'playlist': 'false'}).content)[(- 1)]
self._re... |
def locate_files(file, subdir=None):
if (subdir is None):
subdir = '.'
resdirs = util.listdir(ops.RESDIR, includeFiles=False)
files = []
for resdir in resdirs:
if ((resdir.lower() == 'ops') or (resdir.lower() == 'dsz')):
continue
fullpath = os.path.normpath(os.path.jo... |
def get_dial(dialogue):
dial = []
d_orig = analyze_dialogue(dialogue, MAX_LENGTH)
if (d_orig is None):
return None
usr = [t['text'] for t in d_orig['usr_log']]
sys = [t['text'] for t in d_orig['sys_log']]
sys_a = [t['dialogue_acts'] for t in d_orig['sys_log']]
bvs = [t['belief_value_... |
def default_fsaf_classification_model(num_classes, pyramid_feature_size=256, prior_probability=0.01, classification_feature_size=256, name='fsaf_classification_model'):
options = {'kernel_size': 3, 'strides': 1, 'padding': 'same'}
inputs = keras.layers.Input(shape=(None, None, pyramid_feature_size))
outputs... |
class BertTokenizerMismatchTest(unittest.TestCase):
def test_tokenizer_mismatch_warning(self):
EXAMPLE_BERT_JAPANESE_ID = 'cl-tohoku/bert-base-japanese'
with self.assertLogs('transformers', level='WARNING') as cm:
BertTokenizer.from_pretrained(EXAMPLE_BERT_JAPANESE_ID)
self.a... |
def parse_args():
special_args = [{'name': ['-s', '--size'], 'default': '10000', 'metavar': 'n', 'type': int, 'help': "The array size n in n^2 (default 10000). For 'svd' operation the second dimension is given by --second-size."}, {'name': ['-2', '--second-size'], 'default': '1000', 'type': int, 'help': "The second... |
class _Transition(nn.Sequential):
def __init__(self, num_input_features, num_output_features):
super(_Transition, self).__init__()
self.add_module('norm', nn.BatchNorm3d(num_input_features))
self.add_module('relu', nn.ReLU(inplace=True))
self.add_module('conv', nn.Conv3d(num_input_fe... |
class TestNetcdfEncodingKwargs():
()
def scene(self):
scn = Scene()
attrs = {'start_time': datetime(2018, 5, 30, 10, 0), 'end_time': datetime(2018, 5, 30, 10, 15)}
scn['test-array'] = xr.DataArray([1.0, 2, 3], attrs=attrs)
return scn
(params=[True, False])
def compression... |
def _dynamic_dict(example, src_field, tgt_field):
src = src_field.tokenize(example['src'])
unk = src_field.unk_token
pad = src_field.pad_token
src_ex_vocab = Vocab(Counter(src), specials=[unk, pad])
unk_idx = src_ex_vocab.stoi[unk]
src_map = torch.LongTensor([src_ex_vocab.stoi[w] for w in src])
... |
def test_module_metadata_is_fixed_up() -> None:
import trio
import trio.testing
assert (trio.Cancelled.__module__ == 'trio')
assert (trio.open_nursery.__module__ == 'trio')
assert (trio.abc.Stream.__module__ == 'trio.abc')
assert (trio.lowlevel.wait_task_rescheduled.__module__ == 'trio.lowlevel'... |
_fixtures(WebFixture)
def test_adding_items_with_captions(web_fixture):
carousel = Carousel(web_fixture.view, 'my_carousel_id')
caption_widget = Widget(web_fixture.view)
carousel_item = carousel.add_slide(Img(web_fixture.view), caption_widget=caption_widget)
[image, div_containing_caption] = carousel_it... |
def _train_labeler(args):
if (args.data_setup == 'joint'):
(train_gen_list, val_gen_list, crowd_dev_gen, elmo, bert, vocab) = get_joint_datasets(args)
else:
train_fname = args.train_data
dev_fname = args.dev_data
print(train_fname, dev_fname)
(data_gens, elmo) = get_datas... |
class ResNet(nn.Module):
def __init__(self, depth, num_classes=1000, block_name='BasicBlock'):
super(ResNet, self).__init__()
if (block_name.lower() == 'basicblock'):
assert (((depth - 2) % 6) == 0), 'When use basicblock, depth should be 6n+2, e.g. 20, 32, 44, 56, 110, 1202'
... |
class TestTopLevelCodeChecker(pylint.testutils.CheckerTestCase):
CHECKER_CLASS = TopLevelCodeChecker
CONFIG = {}
def test_message_simple(self):
src = '\n print("testing code")\n '
mod = astroid.parse(src)
with self.assertAddsMessages(pylint.testutils.MessageTest(msg_id=... |
def predict(input_dict, output_stride=16):
image = input_dict['image']
org_shape = tf.shape(image)
affinity = affinity_seg(image, output_stride)
curr_shape = tf.shape(affinity)
affinity = tf.image.resize_bilinear(affinity, [(curr_shape[1] * output_stride), (curr_shape[2] * output_stride)])
affin... |
.parametrize('url, rev', [('git+ None), ('git+ 'master')])
def test_add_git_constraint_with_subdirectory(url: str, rev: (str | None), app: PoetryTestApplication, tester: CommandTester) -> None:
tester.execute(url)
expected = 'Updating dependencies\nResolving dependencies...\n\nPackage operations: 1 install, 0 u... |
class VectorInputWidget(QWidget):
def __init__(self, velocity, obj=None, parent=None):
super(VectorInputWidget, self).__init__(parent)
self.valueTypes = ['Cartisan components']
NumberOfComponents = 3
vector_config = [['vector'], ['vector'], ['vector'], ['Vx', 'Vy', 'Vz'], (['m/s'] * ... |
def test_variables__multiple_specs(dummy_ds: xr.Dataset) -> None:
spec = ArrayLikeSpec('baz', 'baz doc', kind='i', ndim=1)
invalid_spec = ArrayLikeSpec('baz', 'baz doc', kind='i', ndim=2)
variables.validate(dummy_ds, {'foo': spec, 'bar': spec})
variables.validate(dummy_ds, {'foo': spec})
variables.v... |
def subdivide_edges(bm, edges, direction, widths):
dir = direction.copy().normalized()
cuts = (len(widths) - 1)
res = bmesh.ops.subdivide_edges(bm, edges=edges, cuts=cuts)
inner_edges = filter_geom(res.get('geom_inner'), BMEdge)
distance = (sum(widths) / len(widths))
final_position = 0.0
for... |
class TestDataPrep(unittest.TestCase):
def test_process_rxn_templates(self):
path_to_rxn_templates = './data/rxn_set_hb_test.txt'
path_to_building_blocks = './data/building_blocks_matched.csv.gz'
building_blocks = pd.read_csv(path_to_building_blocks, compression='gzip')['SMILES'].tolist()
... |
def replace_registered_tbes_with_mock_tbes(M: torch.nn.Module, path: str='') -> None:
for (child_name, child) in M.named_children():
child_path = (f'{path}.{child_name}' if path else child_name)
if isinstance(child, IntNBitTableBatchedEmbeddingBagsCodegen):
M.register_module(child_name, ... |
class OpenRole(ScrimsButton):
def __init__(self, ctx: Context, letter: str):
super().__init__(emoji=ri(letter))
self.ctx = ctx
async def callback(self, interaction: Interaction):
(await interaction.response.defer())
m = (await self.ctx.simple('Mention the role you want to open re... |
def test_set_size_2w() -> None:
instance = printer.Dummy()
instance.set_with_default(double_width=True)
expected_sequence = (TXT_NORMAL, TXT_STYLE['size']['2w'], TXT_STYLE['flip'][False], TXT_STYLE['smooth'][False], TXT_STYLE['bold'][False], TXT_STYLE['underline'][0], SET_FONT(b'\x00'), TXT_STYLE['align']['... |
.skipif((python_implementation() == 'PyPy'), reason='no orjson on PyPy')
(everythings(min_int=(- ), max_int=, allow_inf=False), booleans())
def test_orjson_converter(everything: Everything, detailed_validation: bool):
from cattrs.preconf.orjson import make_converter as orjson_make_converter
converter = orjson_m... |
def flatten(*args, keep_none=False):
t = []
for arg in args:
if (arg is None):
if keep_none:
t.append(arg)
elif isinstance(arg, (str, range, Domain)):
t.append(arg)
elif isinstance(arg, types.GeneratorType):
res = list(arg)
... |
def _parse_pylint_stdio_result(document, stdout):
diagnostics = []
lines = stdout.splitlines()
for raw_line in lines:
parsed_line = re.match('(.*):(\\d*):(\\d*): (\\w*): (.*)', raw_line)
if (not parsed_line):
log.debug("Pylint output parser can't parse line '%s'", raw_line)
... |
_settings(PRETIX_WEBHOOK_SECRET='secret')
def test_cannot_call_pretix_webhook_with_incorrect_basic_auth(rest_api_client):
rest_api_client.basic_auth('pretix', 'incorrect')
response = rest_api_client.post(reverse('pretix-webhook'))
assert (response.status_code == 401)
assert ('Incorrect authentication cr... |
class Amm():
def __init__(self, x_1: Token, x_2: Token):
if (x_1.name != 'x_1'):
raise Exception('must be 1')
if (x_2.name != 'x_2'):
raise Exception('must be 2')
self.x_1 = x_1.qty
self.x_2 = x_2.qty
self.invariant = (self.x_1 * self.x_2)
self... |
class TestTrainingExtensionsChannelPruningCostCalculator(unittest.TestCase):
def test_calculate_channel_pruning_cost_all_layers(self):
model = mnist_torch_model.Net().to('cpu')
print(model)
input_shape = (1, 1, 28, 28)
dummy_input = create_rand_tensors_given_shapes(input_shape, get_d... |
def main():
try:
session = rs.Session()
js = rs.job.Service('pbspro://localhost/', session=session)
jd = rs.job.Description()
jd.wall_time_limit = 1
jd.executable = '/bin/date'
jd.total_cpu_count = 36
jd.queue = 'regular'
jd.project = 'URTG0014'
... |
def infer_metric_tags_from_eval_results(eval_results):
if (eval_results is None):
return {}
result = {}
for key in eval_results.keys():
if (key.lower().replace(' ', '_') in METRIC_TAGS):
result[key.lower().replace(' ', '_')] = key
elif (key.lower() == 'rouge1'):
... |
class DeclineChatJoinRequest():
async def decline_chat_join_request(self: 'pyrogram.Client', chat_id: Union[(int, str)], user_id: int) -> bool:
(await self.invoke(raw.functions.messages.HideChatJoinRequest(peer=(await self.resolve_peer(chat_id)), user_id=(await self.resolve_peer(user_id)), approved=False)))... |
def ria(phi=1.0, direction=None, mechanism=(), purview=(), partition=None, repertoire=None, partitioned_repertoire=None):
return models.RepertoireIrreducibilityAnalysis(phi=phi, direction=direction, mechanism=mechanism, purview=purview, partition=partition, repertoire=repertoire, partitioned_repertoire=partitioned_... |
def detect_first_second_person(text):
text = text.replace('', '"').replace('', '"').replace('\n', ' ')
text = text.split('"')
for i in range(0, len(text), 2):
if any([(s in ((' ' + text[i]) + ' ')) for s in ['I ', "I'", ' my ', 'My ', ' me ', 'Me.', 'Me ', ' you ', " you'", 'You ', "You'", ' we ', '... |
class TestResultsModifyingParseAction(PyparsingExpressionTestCase):
def compute_stats_parse_action(t):
t['sum'] = sum(t)
t['ave'] = (sum(t) / len(t))
t['min'] = min(t)
t['max'] = max(t)
tests = [PpTestSpec(desc='A parse action that adds new key-values', expr=pp.pyparsing_common.i... |
class Color(Adjustment):
def process(self, old_face, new_face, raw_mask):
clip = self.config.get('clip', True)
preserve_paper = self.config.get('preserve_paper', True)
source = cv2.cvtColor(np.rint(((old_face * raw_mask) * 255.0)).astype('uint8'), cv2.COLOR_BGR2LAB).astype('float32')
... |
def get_args():
parser = argparse.ArgumentParser(description='process the textgrid files')
parser.add_argument('--path', type=str, required=True, help='Data path')
parser.add_argument('--no-overlap', type=strtobool, default=False, help='Whether to ignore the overlapping utterances.')
parser.add_argument... |
class MutableByteHashmapStrategy(HashmapStrategy):
import_from_mixin(UnwrappedHashmapStrategyMixin)
(erase, unerase) = rerased.new_static_erasing_pair('byte-hashmap-strategy')
def is_correct_type(self, w_obj):
return isinstance(w_obj, values.W_MutableBytes)
def wrap(self, val):
return va... |
(on_setattr=attr.setters.validate)
class ValidatedSetter():
a: int
b: str = attr.ib(on_setattr=attr.setters.NO_OP)
c: bool = attr.ib(on_setattr=attr.setters.frozen)
d: int = attr.ib(on_setattr=[attr.setters.convert, attr.setters.validate])
e: bool = attr.ib(on_setattr=attr.setters.pipe(attr.setters.... |
def intersect(ifst1, ifst2, connect=True, compose_filter='auto'):
try:
compose_filter = _getters.GetComposeFilter(compose_filter)
except ValueError:
raise ValueError('Unknown compose filter: {!r}'.format(compose_filter))
ofst = ifst1._mutable_fst_type()
ifst1._ops.intersect(ifst1, ifst2,... |
class Program(Loader):
EXTERN_SYM_BASE =
EXTERN_SYM_SIZE = 4096
BASE_STACK =
END_STACK =
def __init__(self, path: PathLike):
super(Program, self).__init__(path)
self.path: Path = Path(path)
if (not self.path.is_file()):
raise FileNotFoundError(f'file {path} not... |
class MonkeyPatch():
def __init__(self) -> None:
self._setattr: List[Tuple[(object, str, object)]] = []
self._setitem: List[Tuple[(Mapping[(Any, Any)], object, object)]] = []
self._cwd: Optional[str] = None
self._savesyspath: Optional[List[str]] = None
def context(cls) -> Generat... |
class TestDefaultEnvFile(EnvironmentTestCase):
def test_run_with_default_env_file(self, runner, target, env1):
env = self.run_environ(runner, *target, '--default-env-file', env1)
assert (env.get('SECRET') == 'unknown')
assert (env.get('PASSWORD') == 'sweet')
assert (env.get('PATH') =... |
def build_roi_heads(cfg):
roi_heads = []
if (not cfg.MODEL.RPN_ONLY):
roi_heads.append(('box', build_roi_box_head(cfg)))
if cfg.MODEL.MASK_ON:
roi_heads.append(('mask', build_roi_mask_head(cfg)))
if cfg.MODEL.KEYPOINT_ON:
roi_heads.append(('keypoint', build_roi_keypoint_head(cfg)... |
def checkThisFile(f):
if isinstance(f, git.Diff):
if (f.deleted_file or (f.b_blob.size == 0)):
return False
f = f.b_path
elif ((not os.path.exists(f)) or (os.stat(f).st_size == 0)):
return False
for exempt in ExemptFiles:
if exempt.search(f):
return Fa... |
class WebEngineAudio(browsertab.AbstractAudio):
_widget: webview.WebEngineView
def __init__(self, tab, parent=None):
super().__init__(tab, parent)
self._overridden = False
delay_ms = 2000
self._silence_timer = QTimer(self)
self._silence_timer.setSingleShot(True)
s... |
class TestPersistence(TestCase):
def test_unitquantity_persistence(self):
x = pq.m
y = pickle.loads(pickle.dumps(x))
self.assertQuantityEqual(x, y)
x = pq.CompoundUnit('pc/cm**3')
y = pickle.loads(pickle.dumps(x))
self.assertQuantityEqual(x, y)
def test_quantity_p... |
class GarbageCollectorTest(unittest.TestCase):
def test_garbage_collector_call_count_train(self) -> None:
input_dim = 2
dataset_len = 10
batch_size = 2
max_epochs = 2
expected_num_total_steps = ((dataset_len / batch_size) * max_epochs)
my_unit = DummyTrainUnit(2)
... |
class PFSError(enum.IntEnum):
INVALID_REQUEST = 2000
INVALID_SIGNATURE = 2001
REQUEST_OUTDATED = 2002
BAD_IOU = 2100
MISSING_IOU = 2101
WRONG_IOU_RECIPIENT = 2102
IOU_EXPIRED_TOO_EARLY = 2103
INSUFFICIENT_SERVICE_PAYMENT = 2104
IOU_ALREADY_CLAIMED = 2105
USE_THIS_IOU = 2106
D... |
class ELBO_NF(object):
def __init__(self, criterion, num_samples, temperature=1.0):
self.criterion = criterion
self.num_samples = num_samples
self.temperature = temperature
def __call__(self, model, input, target):
t = model.flow.sample()
output = model(input, t=t)
... |
class UseThenDisconnect(object):
def __init__(self, config_object):
self.config_object = config_object
def __enter__(self):
pass
def __exit__(self, typ, value, traceback):
if (self.config_object.get('TESTING') is True):
return
close_db_filter(None) |
class ListRefresher(QThread):
infos = pyqtSignal(object)
err_msg = pyqtSignal(str, int)
def __init__(self, parent=None):
super(ListRefresher, self).__init__(parent)
self._disk = None
self._fid = (- 1)
self.r_files = True
self.r_folders = True
self.r_path = Tru... |
class TToggledPlayOrderMenu(TestCase):
def setUp(self):
self.orders = Orders([OrderShuffle, OrderWeighted, FakeOrder])
self.tpom = ToggledPlayOrderMenu(Icons.AUDIO_X_GENERIC, orders=self.orders, current_order=OrderShuffle, enabled=True)
def tearDown(self):
self.tpom.destroy()
def tes... |
class Color(SObject):
name__ = String.T(optional=True)
r__ = Component.T(default=0.0, help='Red component ``[0., 1.]``.')
g__ = Component.T(default=0.0, help='Green component ``[0., 1.]``.')
b__ = Component.T(default=0.0, help='Blue component ``[0., 1.]``.')
a__ = Component.T(default=1.0, help='Alph... |
class BBCodeLexer(RegexLexer):
name = 'BBCode'
aliases = ['bbcode']
mimetypes = ['text/x-bbcode']
url = '
version_added = '0.6'
tokens = {'root': [('[^[]+', Text), ('\\[/?\\w+', Keyword, 'tag'), ('\\[', Text)], 'tag': [('\\s+', Text), ('(\\w+)(=)("?[^\\s"\\]]+"?)', bygroups(Name.Attribute, Opera... |
class Objdict(dict):
def __getattr__(self, name):
if (name in self):
return self[name]
else:
raise AttributeError(('No such attribute: ' + name))
def __setattr__(self, name, value):
self[name] = value
def __delattr__(self, name):
if (name in self):
... |
class SignedDataEntityHandler(ContextEntityHandler):
def credential_username(self, entity_reference):
return None
def get_serialized_entity_reference(self, entity_reference):
raise NotImplementedError
def deserialize_entity_reference(self, serialized_entity_reference):
raise NotImple... |
def train(training_data_loader, G_optimizer, D_optimizer, model, discr, criterion, epoch):
lr = adjust_learning_rate(D_optimizer, (epoch - 1))
mse = []
Gloss = []
Dloss = []
for param_group in G_optimizer.param_groups:
param_group['lr'] = (lr / 2)
for param_group in D_optimizer.param_gro... |
class NLLModel(nn.Module):
def __init__(self, args):
super().__init__()
self.args = args
self.models = nn.ModuleList()
self.device = [(i % args.n_gpu) for i in range(args.n_model)]
self.loss_fnt = nn.CrossEntropyLoss()
for i in range(args.n_model):
model =... |
class AttrVI_ATTR_MANF_NAME(Attribute):
resources = [(constants.InterfaceType.pxi, 'INSTR'), (constants.InterfaceType.pxi, 'BACKPLANE'), (constants.InterfaceType.usb, 'INSTR'), (constants.InterfaceType.usb, 'RAW'), (constants.InterfaceType.vxi, 'INSTR')]
py_name = 'manufacturer_name'
visa_name = 'VI_ATTR_MA... |
def test_missile_cosmetic_dropdown(skip_qtbot: pytestqt.qtbot.QtBot) -> None:
cosmetic_patches = DreadCosmeticPatches(missile_cosmetic=DreadMissileCosmeticType.NONE)
dialog = DreadCosmeticPatchesDialog(None, cosmetic_patches)
skip_qtbot.addWidget(dialog)
set_combo_with_value(dialog.missile_cosmetic_drop... |
def elf_references_PyFPE_jbuf(elf: ELFFile) -> bool:
offending_symbol_names = ('PyFPE_jbuf', 'PyFPE_dummy', 'PyFPE_counter')
section = elf.get_section_by_name('.dynsym')
if (section is not None):
for sym in section.iter_symbols():
if ((sym.name in offending_symbol_names) and (sym['st_shn... |
class Object3d(object):
def __init__(self, line):
label = line.strip().split(' ')
self.src = line
self.cls_type = label[0]
self.cls_id = cls_type_to_id(self.cls_type)
self.truncation = float(label[1])
self.occlusion = float(label[2])
self.alpha = float(label[3... |
def test_pylsp_format_document_with_config(config, config_document):
result = pylsp_format_document(config, config_document)
assert (result == [{'range': {'start': {'line': 0, 'character': 0}, 'end': {'line': 1, 'character': 0}}, 'newText': 'run(\n these,\n arguments,\n should,\n be,\n wrapped,\n... |
class TestRArray(unittest.TestCase):
def test_basics(self) -> None:
a = RArray(int_rprimitive, 10)
assert (a.item_type == int_rprimitive)
assert (a.length == 10)
def test_str_conversion(self) -> None:
a = RArray(int_rprimitive, 10)
assert (str(a) == 'int[10]')
ass... |
def _merge_a_into_b(a: CfgNode, b: CfgNode, root: CfgNode, key_list: list):
_assert_with_logging(isinstance(a, CfgNode), '`a` (cur type {}) must be an instance of {}'.format(type(a), CfgNode))
_assert_with_logging(isinstance(b, CfgNode), '`b` (cur type {}) must be an instance of {}'.format(type(b), CfgNode))
... |
def autolink(pattern: str, prefix: str):
def role(name, rawtext, text: str, lineno, inliner, options=None, content=None):
if (options is None):
options = {}
url = pattern.format(text)
node = nodes.reference(rawtext, f'{prefix}{text}', refuri=url, **options)
return ([node]... |
(base=CrawlerTask, bind=True)
def crawl_ptt_post(self, url: str, board: str) -> Optional[Dict]:
logger.info('Crawl %s', url)
try:
post = ptt.crawl_post(url, board)
except (IndexError, HTTPError):
logger.error('Could not crawl %s', url)
return
if (not post):
logger.error('... |
def apply_adaround_and_find_quantized_accuracy(model: torch.nn.Module, evaluator: aimet_common.defs.EvalFunction, data_loader: torch_data.DataLoader, use_cuda: bool=False, logdir: str='') -> float:
bn_folded_model = copy.deepcopy(model)
_ = fold_all_batch_norms(bn_folded_model, input_shapes=(1, 3, 224, 224))
... |
class SmilesRnnDistributionLearner():
def __init__(self, output_dir: str, n_epochs=10, hidden_size=512, n_layers=3, max_len=100, batch_size=64, rnn_dropout=0.2, lr=0.001, valid_every=100) -> None:
self.n_epochs = n_epochs
self.output_dir = output_dir
self.hidden_size = hidden_size
se... |
class AdornedRetort(OperatingRetort):
def __init__(self, *, recipe: Iterable[Provider]=(), strict_coercion: bool=True, debug_trail: DebugTrail=DebugTrail.ALL):
self._strict_coercion = strict_coercion
self._debug_trail = debug_trail
super().__init__(recipe)
def _calculate_derived(self):
... |
class Process(nn.Module):
def __init__(self, feature, norm_layer, bn_momentum, dilations=[1, 2, 3]):
super(Process, self).__init__()
self.main = nn.Sequential(*[Bottleneck3D(feature, (feature // 4), bn_momentum=bn_momentum, norm_layer=norm_layer, dilation=[i, i, i]) for i in dilations])
def forw... |
class Effect6507(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Capital Hybrid Turret')), 'speed', src.getModifiedItemAttr('shipBonusDreadnoughtG2'), skill='Gallente Dreadnought', **kwargs) |
def CutoutAbs(img, v, **kwarg):
(w, h) = img.size
x0 = np.random.uniform(0, w)
y0 = np.random.uniform(0, h)
x0 = int(max(0, (x0 - (v / 2.0))))
y0 = int(max(0, (y0 - (v / 2.0))))
x1 = int(min(w, (x0 + v)))
y1 = int(min(h, (y0 + v)))
xy = (x0, y0, x1, y1)
color = (127, 127, 127)
im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.