code stringlengths 281 23.7M |
|---|
class NotEinhornWorkerTests(unittest.TestCase):
def test_is_not_worker(self):
self.assertFalse(einhorn.is_worker())
def test_get_socket_count(self):
with self.assertRaises(einhorn.NotEinhornWorker):
einhorn.get_socket_count()
def test_get_socket(self):
with self.assertRai... |
class IXIBrainInferDataset(Dataset):
def __init__(self, data_path, atlas_path, transforms):
self.atlas_path = atlas_path
self.paths = data_path
self.transforms = transforms
def one_hot(self, img, C):
out = np.zeros((C, img.shape[1], img.shape[2], img.shape[3]))
for i in r... |
class ChineseCLIPFeatureExtractor(ChineseCLIPImageProcessor):
def __init__(self, *args, **kwargs) -> None:
warnings.warn('The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please use ChineseCLIPImageProcessor instead.', FutureWarning)
super().__ini... |
def get_all_tilted_square_lattice_executables(*, n_instances=10, n_repetitions=1000, min_side_length=2, max_side_length=8, side_length_step=2, macrocycle_depths=None, seed=52, twoq_gate_name='sqrt_iswap') -> QuantumExecutableGroup:
rs = np.random.RandomState(seed)
specs = get_all_tilted_square_lattice_specs(n_i... |
class CmdMail(default_cmds.MuxAccountCommand):
key = ''
aliases = ['mail']
lock = 'cmd:all()'
help_category = 'General'
def parse(self):
super().parse()
self.caller_is_account = bool(inherits_from(self.caller, 'evennia.accounts.accounts.DefaultAccount'))
def search_targets(self, ... |
class Effect6771(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
lvl = src.level
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Shield Command')), 'buffDuration', (src.getModifiedItemAttr('durationBonus') * lvl), **kwargs) |
def noisyDataTraining(qnnArch, initialUnitaries, trainingData, noisyData, lda, ep, trainingRounds, numData, stepSize, alertP=0):
noisyDataPlot = [[], []]
i = 0
while (i <= numData):
if (alertP > 0):
print((('Currently at ' + str((i / numData))) + '% noisy data.'))
testData1 = sam... |
class STSEval(object):
def loadFile(self, fpath):
self.data = {}
self.samples = []
for dataset in self.datasets:
(sent1, sent2) = zip(*[l.split('\t') for l in io.open((fpath + ('/STS.input.%s.txt' % dataset)), encoding='utf8').read().splitlines()])
raw_scores = np.arr... |
class SynapseDataset(Dataset):
def __init__(self, keys, args, mode='train'):
super().__init__()
self.patch_size = (args.img_size, args.img_size)
self.files = []
self.mode = mode
for key in keys:
key = key.split('.')[0]
slices = subfiles(join(args.data_... |
class SizeProjectMetadataFilter(FilterMetadataPlugin, AllowListProject):
name = 'size_project_metadata'
initialized = False
max_package_size: int = 0
allowlist_package_names: list[str] = []
def initialize_plugin(self) -> None:
if (not self.initialized):
try:
human... |
class Effect2302(BaseEffect):
type = 'passive'
def handler(fit, module, context, projectionRange, **kwargs):
for (layer, attrPrefix) in (('shield', 'shield'), ('armor', 'armor'), ('hull', '')):
for damageType in ('Kinetic', 'Thermal', 'Explosive', 'Em'):
bonus = ('%s%sDamageR... |
class SetChannel(discord.ui.Button):
def __init__(self, ctx: Context):
super().__init__(emoji=kd(1))
self.ctx = ctx
async def callback(self, interaction: discord.Interaction):
(await interaction.response.defer())
_m = (await self.ctx.simple('Mention the channel you want to use fo... |
def sequence_assigned_stmts(self: (nodes.Tuple | nodes.List), node: node_classes.AssignedStmtsPossibleNode=None, context: (InferenceContext | None)=None, assign_path: (list[int] | None)=None) -> Any:
if (assign_path is None):
assign_path = []
try:
index = self.elts.index(node)
except ValueEr... |
def make_loader(split, dst_cls=DatasetAllTasks, repeat=None, is_training=True, unlabeled=False, task='', transforms_tr=None):
if is_training:
dst = dst_cls(split=split, repeat=repeat, unlabeled=unlabeled, transform=transforms_tr, task=task, num_cls=config.num_cls)
return DataLoader(dst, batch_size=c... |
class SWOCTRL(IntEnum):
CH0OC = (1 << 0)
CH1OC = (1 << 1)
CH2OC = (1 << 2)
CH3OC = (1 << 3)
CH4OC = (1 << 4)
CH5OC = (1 << 5)
CH6OC = (1 << 6)
CH7OC = (1 << 7)
CH0OCV = (1 << 8)
CH1OCV = (1 << 9)
CH2OCV = (1 << 10)
CH3OCV = (1 << 11)
CH4OCV = (1 << 12)
CH5OCV = (1... |
class VariableBatchAll2AllPooledInfo(object):
batch_size_per_rank_per_feature: List[List[int]]
batch_size_per_feature_pre_a2a: List[int]
emb_dim_per_rank_per_feature: List[List[int]]
codecs: Optional[QuantizedCommCodecs] = None
input_splits: Optional[List[int]] = None
output_splits: Optional[Lis... |
_required
_
def reviewer_comments_dashboard(request, conference_slug):
conference = get_object_or_404(Conference, slug=conference_slug)
if (not is_conference_moderator(user=request.user, conference=conference)):
raise PermissionDenied
conference_reviewers = ConferenceProposalReviewer.objects.filter(... |
class TestFindUcs2Symbols():
def test_elf_find_ucs2_symbols(self):
elf = Mock()
asunicode = MockSymbol('PyUnicodeUCS2_AsUnicode', st_shndx='SHN_UNDEF', st_info=dict(type='STT_FUNC'))
symbols = (asunicode, Mock())
symbols[1].name = 'foobar'
elf.get_section_by_name.return_value... |
def get_residual_integral(s1: Spectrum, s2: Spectrum, var, ignore_nan=False, wunit='default', Iunit='default') -> float:
(var, wunit, Iunit) = get_default_units(s1, s2, var=var, wunit=wunit, Iunit=Iunit)
(w1, I1) = s1.get(var, wunit=wunit, Iunit=Iunit)
(wdiff, dI) = get_diff(s1, s2, var, wunit=wunit, Iunit=... |
_jcustomizer.JConversion('com.conveyal.r5.analyst.cluster.AnalysisWorkerTask', exact=RegionalTask)
_jcustomizer.JConversion('com.conveyal.r5.profile.ProfileRequest', exact=RegionalTask)
_jcustomizer.JConversion('com.conveyal.r5.analyst.cluster.RegionalTask', exact=RegionalTask)
def _cast_RegionalTask(java_class, object... |
class ConvGRU(nn.Module):
def __init__(self, hidden_dim=128, input_dim=(192 + 128)):
super(ConvGRU, self).__init__()
self.convz = nn.Conv2d((hidden_dim + input_dim), hidden_dim, 3, padding=1)
self.convr = nn.Conv2d((hidden_dim + input_dim), hidden_dim, 3, padding=1)
self.convq = nn.C... |
def rand_augment_ops(magnitude: Union[(int, float)]=10, prob: float=0.5, hparams: Optional[Dict]=None, transforms: Optional[Union[(Dict, List)]]=None):
hparams = (hparams or _HPARAMS_DEFAULT)
transforms = (transforms or _RAND_TRANSFORMS)
return [AugmentOp(name, prob=prob, magnitude=magnitude, hparams=hparam... |
.parametrize('content_type, expected', [('application/rss', True), ('application/rss; charset=UTF-8', True), ('application/atom', True), ('application/xml', True), ('text/html', False)])
def test_is_feed_content_type(content_type, expected):
assert (helpers.is_feed_content_type(content_type) is expected) |
('PyQt6.QtWidgets.QGraphicsView.mousePressEvent')
def test_mouse_press_pan_middle_drag(mouse_event_mock, view):
event = MagicMock()
event.position.return_value = QtCore.QPointF(10.0, 20.0)
event.button.return_value = Qt.MouseButton.MiddleButton
event.modifiers.return_value = None
view.mousePressEven... |
class MPISolver(Solver):
CHECK_SYNC_ITERS = 1000
def __init__(self, sess, optimizer, vars):
super().__init__(vars)
self.sess = sess
self.optimizer = optimizer
self._build_grad_feed(vars)
self._update = optimizer.apply_gradients(zip(self._grad_tf_list, self.vars))
... |
class NodeScenariosTest(unittest.TestCase):
def setUp(self):
vsphere_env_vars = ['VSPHERE_IP', 'VSPHERE_USERNAME', 'VSPHERE_PASSWORD']
self.credentials_present = all(((env_var in os.environ) for env_var in vsphere_env_vars))
def test_serialization(self):
plugin.test_object_serialization(... |
def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2)):
(filters1, filters2, filters3) = filters
if (K.image_data_format() == 'channels_last'):
bn_axis = 3
else:
bn_axis = 1
conv_name_base = ((('res' + str(stage)) + block) + '_branch')
bn_name_base = ((('bn'... |
def test_git_getdate(wd: WorkDir) -> None:
today = datetime.now(timezone.utc).date()
def parse_date() -> date:
parsed = git.parse(os.fspath(wd.cwd), Configuration())
assert (parsed is not None)
assert (parsed.node_date is not None)
return parsed.node_date
git_wd = git.GitWork... |
def test_offroadcondition():
cond = OSC.OffroadCondition(20)
prettyprint(cond.get_element())
cond2 = OSC.OffroadCondition(20)
cond3 = OSC.OffroadCondition(23)
assert (cond == cond2)
assert (cond != cond3)
cond4 = OSC.OffroadCondition.parse(cond.get_element())
assert (cond == cond4)
a... |
class PyProjectSource(DependencySource):
def __init__(self, filename: Path, index_url: (str | None)=None, extra_index_urls: list[str]=[], state: AuditState=AuditState()) -> None:
self.filename = filename
self.state = state
def collect(self) -> Iterator[Dependency]:
with self.filename.ope... |
def test_ChunkedReader() -> None:
t_body_reader(ChunkedReader, b'0\r\n\r\n', [EndOfMessage()])
t_body_reader(ChunkedReader, b'0\r\nSome: header\r\n\r\n', [EndOfMessage(headers=[('Some', 'header')])])
t_body_reader(ChunkedReader, (((b'5\r\n01234\r\n' + b'10\r\nabcdef\r\n') + b'0\r\n') + b'Some: header\r\n\r\... |
def _iterable_if_range(node: nodes.NodeNG) -> Optional[str]:
if ((not isinstance(node, nodes.Call)) or (not isinstance(node.func, nodes.Name)) or (not (node.func.name == 'range'))):
return None
if (len(node.args) > 1):
arg1 = node.args[0]
if ((not isinstance(arg1, nodes.Const)) or (arg1.... |
class TestAssertIsNotNone(TestCase):
def test_you(self):
assert (abc is not None)
def test_me(self):
assert ((xxx + y) is not None)
assert ((aaa and bbb) is not None)
assert ((ccc or ddd) is not None)
assert ((True if You else False) is not None)
def test_everybody(se... |
class AconC(nn.Module):
def __init__(self, c1):
super().__init__()
self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
self.beta = nn.Parameter(torch.ones(1, c1, 1, 1))
def forward(self, x):
dpx = ((self.p1 - self.p2) * x)
... |
class MyHardSingleTripletSelector():
def __init__(self, nbrs_num, rand_num, nbr_indices):
self.x = None
self.y = None
self.nbrs_num = nbrs_num
self.rand_num = rand_num
self.nbr_indices = nbr_indices
def get_triplets(self, anom_idx, x, y, normal_label=0):
self.x = ... |
class AnyStage(nn.Module):
def __init__(self, w_in, w_out, stride, d, block_class, norm, activation_class, params):
super().__init__()
for i in range(d):
block = block_class(w_in, w_out, stride, norm, activation_class, params)
self.add_module('b{}'.format((i + 1)), block)
... |
def allreduce_grads(model, coalesce=True, bucket_size_mb=(- 1)):
grads = [param.grad.data for param in model.parameters() if (param.requires_grad and (param.grad is not None))]
world_size = dist.get_world_size()
if coalesce:
_allreduce_coalesced(grads, world_size, bucket_size_mb)
else:
f... |
class MSMROpenCircuitPotential(BaseOpenCircuitPotential):
def get_coupled_variables(self, variables):
(domain, Domain) = self.domain_Domain
phase_name = self.phase_name
if (self.reaction == 'lithium-ion main'):
T = variables[f'{Domain} electrode temperature [K]']
doma... |
class TestQueryBestSize(EndianTest):
def setUp(self):
self.req_args_0 = {'drawable': , 'height': 64528, 'item_class': 1, 'width': 8620}
self.req_bin_0 = b'a\x01\x00\x03u\xb4\x8a5!\xac\xfc\x10'
self.reply_args_0 = {'height': 2023, 'sequence_number': 41036, 'width': 35260}
self.reply_b... |
class TransformerDecoderLayer(nn.Module):
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation='relu', normalize_before=False):
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.multihead_attn = nn.MultiheadAttention(d... |
class Generator():
def __init__(self, cnt_round, cnt_gen, dic_path, dic_exp_conf, dic_agent_conf, dic_traffic_env_conf, best_round=None):
self.cnt_round = cnt_round
self.cnt_gen = cnt_gen
self.dic_exp_conf = dic_exp_conf
self.dic_path = dic_path
self.dic_agent_conf = copy.dee... |
class DIAYN(SAC):
def __init__(self, base_kwargs, env, policy, discriminator, qf, vf, pool, plotter=None, lr=0.003, scale_entropy=1, discount=0.99, tau=0.01, num_skills=20, save_full_state=False, find_best_skill_interval=10, best_skill_n_rollouts=10, learn_p_z=False, include_actions=False, add_p_z=True):
Se... |
.requires_internet
def test_unknown_dynamic_feature(hatch, helpers, temp_dir, config_file):
config_file.model.template.plugins['default']['tests'] = False
config_file.save()
project_name = 'My.App'
with temp_dir.as_cwd():
result = hatch('new', project_name)
assert (result.exit_code == 0), re... |
def simplify_hex(s):
if ((s[1] == s[2]) and (s[3] == s[4]) and (s[5] == s[6]) and ((len(s) == 9) and (s[7] == s[8]))):
s = ((((s[0] + s[1]) + s[3]) + s[5]) + (s[7] if (len(s) == 9) else ''))
if ((len(s) == 9) and (s[(- 2):].lower() == 'ff')):
s = s[:7]
elif ((len(s) == 5) and (s[(- 1):].lowe... |
def loadThemes():
def loadThemesFromDir(dname, isBuiltin=False):
if (not os.path.isdir(dname)):
return
for fname in [fname for fname in os.listdir(dname) if fname.endswith('.theme')]:
try:
theme = ssdf.load(os.path.join(dname, fname))
assert (t... |
.skipif((not HAVE_DEPS_FOR_RESOURCE_ESTIMATES), reason='pyscf and/or jax not installed.')
def test_reiher_sf_lambda():
RANK = 200
NAME = path.join(path.dirname(__file__), '../integrals/eri_reiher.h5')
(_, reiher_mf) = load_casfile_to_pyscf(NAME, num_alpha=27, num_beta=27)
(eri_rr, sf_factors) = sf.facto... |
def run_clang_format(src, dst, exe, verbose, inplace):
dstdir = os.path.dirname(dst)
if (not os.path.exists(dstdir)):
os.makedirs(dstdir)
if (src == dst):
cmd = ('%s -i %s' % (exe, src))
else:
cmd = ('%s %s > %s' % (exe, src, dst))
try:
subprocess.check_call(cmd, shel... |
def get_j_bot(x, w, l, s, d, alpha, bs, V, minority, T):
harg = ((x - w) / l)
cosh_harg = np.cosh(harg)
sinh_harg = np.sinh(harg)
lsod = ((l * s) / d)
j_bottom_light = (((((q * bs) * alpha) * l) / (((alpha ** 2) * (l ** 2)) - 1)) * ((l * alpha) - ((((lsod * cosh_harg) + sinh_harg) - ((lsod - (l * al... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('files', nargs='+')
parser.add_argument('-g', '--github-mode', help='Produce output as a GitHub comment', action='store_true')
opts = parser.parse_args()
missing_entries = list(itertools.chain.from_iterable(map(find_missing_entries, ... |
def generate_methods_table(cl: ClassIR, name: str, emitter: Emitter) -> None:
emitter.emit_line(f'static PyMethodDef {name}[] = {{')
for fn in cl.methods.values():
if (fn.decl.is_prop_setter or fn.decl.is_prop_getter):
continue
emitter.emit_line(f'{{"{fn.name}",')
emitter.emi... |
class MemcacheRateLimitBackend(RateLimitBackend):
def __init__(self, memcache: MonitoredMemcacheConnection, prefix: str='rl:'):
self.memcache = memcache
self.prefix = prefix
def consume(self, key: str, amount: int, allowance: int, interval: int) -> bool:
current_bucket = _get_current_buc... |
def test_call_with_keyboard_interrupt(tmp_path: Path, tmp_venv: VirtualEnv, mocker: MockerFixture) -> None:
mocker.patch('subprocess.check_call', side_effect=KeyboardInterrupt())
kwargs = {'call': True}
with pytest.raises(KeyboardInterrupt):
tmp_venv.run('python', '-', **kwargs)
subprocess.check... |
_db
def test_add_custom_item(conference_factory, day_factory, slot_factory, room, admin_graphql_client):
conference = conference_factory(start=datetime(2020, 4, 2, tzinfo=pytz.UTC), end=datetime(2020, 4, 2, tzinfo=pytz.UTC))
day = day_factory(conference=conference, day=date(2020, 4, 2))
slot = slot_factory(... |
class MPM(SPM):
def __init__(self, options=None, name='Many-Particle Model', build=True):
options = (options or {})
if (('particle size' in options) and (options['particle size'] != 'distribution')):
raise pybamm.OptionError("particle size must be 'distribution' for MPM not '{}'".format(... |
class SmilesFeaturizer():
def __init__(self, atm_featurizer: AtmFeaturizer):
self.atm_featurizer = atm_featurizer
self.bond_featurizer = BondFeaturizer()
def smi_to_feats(self, smi: str):
mol = Chem.MolFromSmiles(smi)
atm_feats = torch.stack([self.atm_featurizer.atom_to_feat(atm,... |
def version(draw, min_digits=1, max_digits=None, min_version=None, max_version=None):
min_version_digits = (None if (min_version is None) else len(min_version.split('.')))
max_version_digits = (None if (max_version is None) else len(max_version.split('.')))
if (min_digits < 1):
raise ValueError('Min... |
class STDataArguments():
train_file: str = dataclasses.field(metadata={'help': 'A csv or a json file containing the training data.'})
infer_file: str = dataclasses.field(metadata={'help': 'A csv or a json file containing the data to predict on.'})
eval_file: Optional[str] = dataclasses.field(default=None, m... |
def test_mros() -> None:
failed_messages = []
for (module_name, module_value) in inspect.getmembers(gitlab.v4.objects):
if (not inspect.ismodule(module_value)):
continue
for (class_name, class_value) in inspect.getmembers(module_value):
if (not inspect.isclass(class_value... |
class BUCCBitextMining(AbsTaskBitextMining, CrosslingualTask):
def description(self):
return {'name': 'BUCC', 'hf_hub_name': 'mteb/bucc-bitext-mining', 'description': 'BUCC bitext mining dataset', 'reference': ' 'type': 'BitextMining', 'category': 's2s', 'eval_splits': ['test'], 'eval_langs': _LANGUAGES, 'm... |
class DatasetIterater(Dataset):
def __init__(self, src, tgt, attention_mask):
self.src = src
self.tgt = tgt
self.attention_mask = attention_mask
def __getitem__(self, index):
return (self.src[index], self.attention_mask[index], self.tgt[index])
def __len__(self):
retu... |
class HybridModel(torch.nn.Module):
def __init__(self, remote_emb_module, device):
super(HybridModel, self).__init__()
self.remote_emb_module = remote_emb_module
self.fc = DDP(torch.nn.Linear(16, 8).cuda(device), device_ids=[device])
self.device = device
def forward(self, indices... |
class FormsDict(MultiDict):
input_encoding = 'utf8'
recode_unicode = True
def _fix(self, s, encoding=None):
if (isinstance(s, unicode) and self.recode_unicode):
return s.encode('latin1').decode((encoding or self.input_encoding))
elif isinstance(s, bytes):
return s.dec... |
class TSynchronizedTextSpec(TestCase):
def test_write(self):
s = SynchronizedTextSpec('name')
f = Frame()
values = [(u'A', 100), (u'axy', 0), (u'', 42), (u'', 0)]
f.encoding = 1
self.assertEqual(s.read(None, f, s.write(None, f, values)), (values, b''))
data = s.write(... |
def just_class_with_type_takes_self(tup):
nested_cl = tup[1][0]
default = attr.Factory((lambda _: nested_cl()), takes_self=True)
combined_attrs = list(tup[0])
combined_attrs.append((attr.ib(default=default, type=nested_cl), st.just(nested_cl())))
return _create_hyp_class(combined_attrs) |
class PolicyNet(nn.Module):
def __init__(self):
super(PolicyNet, self).__init__()
self.fc1 = nn.Linear(4, 24)
self.fc2 = nn.Linear(24, 36)
self.fc3 = nn.Linear(36, 1)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.sigmoid(self.... |
def test_single_marker_union_with_multi_union_is_union_of_single_markers() -> None:
m = parse_marker('python_version >= "3.6"')
union = m.union(parse_marker('python_version < "3.6" and sys_platform == "win32" or python_version < "3.6" and sys_platform == "linux"'))
assert (str(union) == 'sys_platform == "wi... |
def _exit_cleanup():
for cache in USED_CACHES:
target = (cache.processes / os.path.basename(cache.process_pool.path))
try:
cache.lock.__enter__()
except Exception:
continue
else:
try:
if os.path.exists(target):
s... |
class ChatEventFilter(Object):
def __init__(self, *, new_restrictions: bool=False, new_privileges: bool=False, new_members: bool=False, chat_info: bool=False, chat_settings: bool=False, invite_links: bool=False, deleted_messages: bool=False, edited_messages: bool=False, pinned_messages: bool=False, leaving_members:... |
def test_pattern_commonconc_suffix() -> None:
assert (str(parse('a|bc')._commonconc(suffix=True)) == '')
assert (str(parse('aa|bca')._commonconc(suffix=True)) == 'a')
assert (str(parse('xyza|abca|a')._commonconc(suffix=True)) == 'a')
assert (str(parse('f{2,3}c|fc')._commonconc(suffix=True)) == 'fc')
... |
def prepare_datasets(config):
data = {}
if (config['data_type'] == 'network'):
(adj, features, labels, idx_train, idx_val, idx_test) = network_data_utils.load_data(config['data_dir'], config['dataset_name'], knn_size=config.get('input_graph_knn_size', None), epsilon=config.get('input_graph_epsilon', Non... |
def convert(pronunc, source, dest):
assert (type(pronunc) in [bytes, unicode, list]), type(pronunc)
if (source == dest):
return pronunc
if (type(pronunc) == list):
return [convert(p, source, dest) for p in pronunc]
func = checkSetting(source, 'cvtOut_func')
if func:
pronunc =... |
def test_unicode_conversion():
assert (m.good_utf8_string() == u'Say utf8 A')
assert (m.good_utf16_string() == u'bAz')
assert (m.good_utf32_string() == u'aAz')
assert (m.good_wchar_string() == u'aAz')
with pytest.raises(UnicodeDecodeError):
m.bad_utf8_string()
with pytest.raises(Unicode... |
class kmod_info_t(ctypes.Structure):
_pack_ = 8
_fields_ = (('next', POINTER64), ('info_version', ctypes.c_int32), ('id', ctypes.c_uint32), ('name', (ctypes.c_char * 64)), ('version', (ctypes.c_char * 64)), ('reference_count', ctypes.c_int32), ('reference_list', POINTER64), ('address', POINTER64), ('size', ctyp... |
class aggregation(nn.Module):
def __init__(self, channel):
super(aggregation, self).__init__()
self.relu = nn.ReLU(True)
self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
self.conv_upsample1 = nn.Conv2d(channel, channel, 3, padding=1)
self.conv_... |
class PythonQuery(QueryPlugin):
PLUGIN_ID = 'python_query'
PLUGIN_NAME = _('Python Query')
PLUGIN_DESC = _('Use Python expressions in queries.')
key = 'python'
query_syntax = _('(python: expression)')
query_description = _('The variable <tt>s</tt> (or <tt>a</tt>) is the song / album being matche... |
def _make_prepare_uv():
from qualtran.bloqs.chemistry.pbc.first_quantization.prepare_uv import PrepareUVFirstQuantization
num_bits_p = 5
eta = 10
num_atoms = 10
lambda_zeta = 10
m_param = (2 ** 8)
num_bits_nuc_pos = 16
prep = PrepareUVFirstQuantization(num_bits_p=num_bits_p, eta=eta, num... |
def test_load_backoff_callable_absolute():
f = backoffcache.load_backoff_callable('tests.arbpack.arbcallables.ArbCallable')
callable_ref = f('ctor in')
assert (callable_ref('arg in 1') == 'from callable: ctor in arg in 1')
assert (callable_ref('arg in 2') == 'from callable: ctor in arg in 2') |
def get_port_for_service(app: AppDef) -> str:
port = '29500'
for (role_idx, role) in enumerate(app.roles):
if (role.port_map is None):
continue
for value in role.port_map.values():
port = str(value)
if (not (0 < int(port) <= 65535)):
msg = 'Warning: port_map s... |
.parametrize('username,password,email', site_managers)
def test_is_site_manager_returns_false_when_role_doesnotexist_(db, client, username, password, email):
client.login(username=username, password=password)
Role.objects.all().delete()
user = get_user_model().objects.get(username=username, email=email)
... |
def human_readable_time(timestamp):
date = datetime.fromtimestamp(timestamp)
datediff = (datetime.now().date() - date.date())
if (datediff.days >= 365):
return date.strftime('%-d %b %Y')
elif (datediff.days >= 7):
return date.strftime('%-d %b')
elif (datediff.days >= 1):
retu... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--profile', type=str, action='store', help='The credentials.response profile to use.')
parser.add_argument('--prefix', type=str, action='store', help='Output filename prefix.')
s = parser.add_mutually_exclusive_group(required=False)
... |
def import_objects(manage_dict):
auto_import = {}
auto_scripts = []
import_dict = manage_dict.get('shell', {}).get('auto_import', {})
object_list = import_dict.get('objects', [])
if isinstance(object_list, dict):
for (name, spec) in object_list.items():
_obj = import_module(name)... |
class _Arguments():
modules: list[str]
concise: bool
ignore_missing_stub: bool
ignore_positional_only: bool
allowlist: list[str]
generate_allowlist: bool
ignore_unused_allowlist: bool
mypy_config_file: str
custom_typeshed_dir: str
check_typeshed: bool
version: str |
def test(epoch, criterion_cls, criterion_div):
net.eval()
global best_acc
test_loss_cls = 0.0
test_loss_div = 0.0
correct = ([0] * (args.num_branches + 1))
total = ([0] * (args.num_branches + 1))
with torch.no_grad():
for (batch_idx, (inputs, target)) in enumerate(testloader):
... |
def visualize_solution(xc, yc, x, C, n, K, title_str):
plt.figure()
plt.scatter(xc, yc, s=200)
for i in range(len(xc)):
plt.annotate(i, ((xc[i] + 0.15), yc[i]), size=16, color='r')
plt.plot(xc[0], yc[0], 'r*', ms=20)
plt.grid()
for ii in range(0, (n ** 2)):
if (x[ii] > 0):
... |
class Tokens(object):
TEXT = 0
TEXT_WS = 1
SPAN = 2
POS = 3
LEMMA = 4
NER = 5
def __init__(self, data, annotators, opts=None):
self.data = data
self.annotators = annotators
self.opts = (opts or {})
def __len__(self):
return len(self.data)
def slice(sel... |
class ReduceScatterBase_Req(Function):
def forward(ctx, pg: dist.ProcessGroup, myreq: Request[Tensor], rsi: ReduceScatterBaseInfo, inputs: Tensor) -> Tensor:
my_size = dist.get_world_size(pg)
assert ((inputs.size(0) % my_size) == 0)
if (rsi.codecs is not None):
inputs = rsi.codec... |
class CustomHandler(Handler):
def __init__(self, uuid='', logs='', custom_filter=None, config=None, drop=False):
self.db = {'db_postgres': None, 'db_sqlite': None}
self.logs = logs
self.uuid = uuid
self.custom_filter = custom_filter
if (config and (config != '') and ('db_post... |
def contrastive_cross_entropy(logits, target, margin=0.0):
logp = F.log_softmax(logits, dim=(- 1))
target_one_hot = F.one_hot(target, num_classes=logp.shape[(- 1)])
logp_target = (logp * target_one_hot.to(logits.dtype)).sum((- 1))
logp_others = torch.where(target_one_hot.to(torch.uint8), torch.full_like... |
class HfTrainerDeepSpeedConfig(HfDeepSpeedConfig):
def __init__(self, config_file_or_dict):
super().__init__(config_file_or_dict)
self._dtype = None
self.mismatches = []
def dtype(self):
if (self._dtype is None):
raise ValueError("trainer_config_process() wasn't calle... |
.unit()
.parametrize(('arg_name', 'arg_value', 'i', 'id_func', 'expected'), [('arg', 1, 0, None, '1'), ('arg', True, 0, None, 'True'), ('arg', False, 0, None, 'False'), ('arg', 1.0, 0, None, '1.0'), ('arg', None, 0, None, 'arg0'), ('arg', (1,), 0, None, 'arg0'), ('arg', [1], 0, None, 'arg0'), ('arg', {1, 2}, 0, None, '... |
def test_jax_FunctionGraph_once():
from pytensor.link.jax.dispatch import jax_funcify
x = vector('x')
y = vector('y')
class TestOp(Op):
def __init__(self):
self.called = 0
def make_node(self, *args):
return Apply(self, list(args), [x.type() for x in args])
... |
class struct__EFI_IFR_VARSTORE(ctypes.Structure):
_pack_ = True
_fields_ = [('Header', EFI_IFR_OP_HEADER), ('PADDING_0', (ctypes.c_ubyte * 2)), ('Guid', EFI_GUID), ('VarStoreId', ctypes.c_uint16), ('Size', ctypes.c_uint16), ('Name', (ctypes.c_ubyte * 1)), ('PADDING_1', (ctypes.c_ubyte * 3))] |
class LithiumIonParameters(BaseParameters):
def __init__(self, options=None):
self.options = options
self.geo = pybamm.GeometricParameters(options)
self.elec = pybamm.electrical_parameters
self.therm = pybamm.thermal_parameters
self.n = DomainLithiumIonParameters('negative', ... |
def test_cohorts_to_array__indexes():
with pytest.raises(ValueError, match='Cohort tuples must all be the same length'):
_cohorts_to_array([(0, 1), (0, 1, 2)])
np.testing.assert_equal(_cohorts_to_array([]), np.array([]))
np.testing.assert_equal(_cohorts_to_array([0, 1]), np.array([[0], [1]]))
np... |
def update_db(dest, src):
for (comp, group) in src.items():
if (comp in dest):
update_db(dest[comp][0], group[0])
update_db(dest[comp][1], group[1])
if (len(group) > 2):
dest[comp] = (dest[comp][:2] + group[2:])
else:
dest[comp] = copy_... |
_torch
_sentencepiece
_tokenizers
_flax
class MT5IntegrationTest(unittest.TestCase):
def test_small_integration_test(self):
model = FlaxMT5ForConditionalGeneration.from_pretrained('google/mt5-small')
tokenizer = AutoTokenizer.from_pretrained('google/mt5-small')
input_ids = tokenizer('Hello t... |
_only
def init_wandb_logger(opt):
import wandb
logger = get_root_logger()
project = opt['logger']['wandb']['project']
resume_id = opt['logger']['wandb'].get('resume_id')
if resume_id:
wandb_id = resume_id
resume = 'allow'
logger.warning(f'Resume wandb logger with id={wandb_id... |
def apply_seq_mse(model: torch.nn.Module, sim: QuantizationSimModel, data_loader: DataLoader, params: SeqMseParams, modules_to_exclude: Optional[List[torch.nn.Module]]=None, module_classes_to_exclude: Optional[List[torch.nn.Module]]=None, checkpoints_config: Optional[str]=None):
assert (sim._quant_scheme == QuantSc... |
def _long_description(dist: 'Distribution', val: _DictOrStr, root_dir: _Path):
from setuptools.config import expand
if isinstance(val, str):
file: Union[(str, list)] = val
text = expand.read_files(file, root_dir)
ctype = _guess_content_type(val)
else:
file = (val.get('file') ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.