code stringlengths 281 23.7M |
|---|
class RequestScope(Scope):
if False:
_local_manager = None
_locals = None
def cleanup(self) -> None:
self._local_manager.cleanup()
def prepare(self) -> None:
self._locals.scope = {}
def configure(self) -> None:
self._locals = Local()
self._local_manager = ... |
def existing_config(file):
text = dedent(' [metadata]\n author = John Doe\n author-email = john.\n license = gpl3\n\n [pyscaffold]\n # Comment\n version = 3.78\n extensions =\n namespace\n tox\n cirrus\n namespace = my_n... |
def to_official(preds, features):
(h_idx, t_idx, title) = ([], [], [])
for f in features:
hts = f['hts']
h_idx += [ht[0] for ht in hts]
t_idx += [ht[1] for ht in hts]
title += [f['title'] for ht in hts]
res = []
for i in range(preds.shape[0]):
pred = preds[i]
... |
class DateTimeOnCriterion(Criterion):
def __init__(self, term, criteria):
super(DateTimeOnCriterion, self).__init__()
self.term = term
self.criteria = criteria
def get_query(self, **kwargs):
term = self.term.get_query(**kwargs)
if isinstance(self.criteria, DateTimeOn):
... |
class INR(nn.Module):
def __init__(self, in_features, hidden_features, hidden_layers, out_features, outermost_linear=True, first_omega_0=30, hidden_omega_0=30, sigma=10.0, pos_encode_configs={'type': None, 'use_nyquist': None, 'scale_B': None, 'mapping_input': None}):
super().__init__()
self.pos_enc... |
_model
def identityformer_s36(pretrained=False, **kwargs):
model = MetaFormer(depths=[6, 6, 18, 6], dims=[64, 128, 320, 512], token_mixers=nn.Identity, norm_layers=partial(LayerNormGeneral, normalized_dim=(1, 2, 3), eps=1e-06, bias=False), **kwargs)
model.default_cfg = default_cfgs['identityformer_s36']
if ... |
def test_dict_from_weights():
weights = ['mbart50', 'mbart-large-50-many-to-many-mmt', 'facebook/mbart-large-50-many-to-many-mmt', 'm2m100', 'm2m100_418M', 'm2m100_1.2B', 'facebook/m2m100_418M', 'facebook/m2m100_1.2B']
valid_keys = ['langs', 'codes', 'pairs']
for w in weights:
assert (type(utils._di... |
def copy_var_format(var, as_var):
if (not hasattr(var, 'dtype')):
return var
rval = var
if (rval.type.dtype != as_var.type.dtype):
rval = rval.astype(as_var.type.dtype)
if (rval.ndim == as_var.ndim):
rval = as_var.type.filter_variable(rval)
else:
tmp = as_var.type.clo... |
def check_comparative(qdmr_args, i_op, qdmr, change_stage=0):
ok = True
corrected = None
ok = (ok and (len(qdmr_args) == 3))
ok = (ok and QdmrInstance.is_good_qdmr_ref(qdmr_args[0], i_op))
ok = (ok and QdmrInstance.is_good_qdmr_ref(qdmr_args[1], i_op))
matches = re.findall(BETWEEN_RE_PATTERN, qd... |
def to_melspec(y, sr, n_fft=400, hop_t=0.01, win_t=0.025, window='hamming', preemphasis=0.97, n_mels=80, log=True, norm_mel=None, log_floor=(- 20)):
spec = rstft(y, sr, n_fft, hop_t, win_t, window, preemphasis, log=False)
hop_length = int((sr * hop_t))
melspec = librosa.feature.melspectrogram(sr=sr, S=spec,... |
.skipif((torch.cuda.device_count() < 2), reason='test requires multi-GPU machine')
.parametrize('num_workers', [1, 2])
def test_load_gpu(tmpdir, ray_start_2_gpus, seed, num_workers):
model = BoringModel()
strategy = HorovodRayStrategy(num_workers=num_workers, use_gpu=True)
trainer = get_trainer(tmpdir, stra... |
def _make_pickup(pickup_category: PickupCategory, generator_params: PickupGeneratorParams):
return PickupEntry(name='Pickup', model=PickupModel(game=RandovaniaGame.METROID_PRIME_ECHOES, name='EnergyTransferModule'), pickup_category=pickup_category, broad_category=pickup_category, progression=(), generator_params=ge... |
def create_disk_folder_split(annotation_path: str, data_path: str, output_path: str):
assert os.path.exists(annotation_path), f'Could not find annotation path {annotation_path}'
assert os.path.exists(data_path), f'Could not find data folder {data_path}'
dataset = _ExtractMiddleFrameDataset(data_path=data_pa... |
class upsampleBlock(nn.Module):
def __init__(self, in_channels, out_channels, activation=relu):
super(upsampleBlock, self).__init__()
self.act = activation
self.pad = nn.ReflectionPad2d(1)
self.conv = nn.Conv2d(in_channels, out_channels, 3, stride=1, padding=0)
self.shuffler ... |
class MultiHeadedAttention(nn.Module):
def __init__(self, h, d_model, dropout=0.1, no_cuda=False):
super(MultiHeadedAttention, self).__init__()
assert ((d_model % h) == 0)
self.d_k = (d_model // h)
self.h = h
self.linears = clones(nn.Linear(d_model, d_model), 4)
self.... |
def get_fixed_samples(env, num_actions, num_samples):
fixed_samples = []
num_environment = env.num_process
env.reset()
for _ in range(0, num_samples, num_environment):
(old_state, action, reward, new_state, is_terminal) = env.get_state()
action = np.random.randint(0, num_actions, size=(n... |
.parametrize('trick_levels', [None, MagicMock()])
def test_click_on_link(echoes_game_description, skip_qtbot, trick_levels):
main_window = QWidget()
main_window.open_data_visualizer_at = MagicMock()
skip_qtbot.add_widget(main_window)
world_name = 'World'
area_name = 'Area'
popup = trick_details_... |
def main():
client = pypilotClient('192.168.14.1')
client.watch('imu.frequency', 1.0)
client.watch('ap.heading', 0.25)
while True:
msgs = client.receive()
if (not msgs):
time.sleep(0.03)
continue
for (name, value) in msgs.items():
print(name, '... |
(frozen=True)
class BenchSchema():
entry_point: Union[(Callable, str)]
base: str
tags: Iterable[str]
kwargs: Mapping[(str, Any)]
used_distributions: Sequence[str]
skip_if: Optional[Callable[([EnvSpec], bool)]] = None
check_params: Callable[([EnvSpec], CheckParams)] = (lambda env_spec: CheckP... |
def test_warning(tmpdir, caplog):
profile = DefaultGTiffProfile(count=1, height=256, width=256, compression='lolwut', foo='bar')
with rasterio.Env(GDAL_VALIDATE_CREATION_OPTIONS=True):
rasterio.open(str(tmpdir.join('test.tif')), 'w', **profile)
assert (set(['CPLE_NotSupported in driver GTiff does no... |
class Product(Resource):
def __init__(self, client=None):
super(Product, self).__init__(client)
self.base_url = (URL.V2 + URL.ACCOUNT)
def requestProductConfiguration(self, account_id, data={}, **kwargs):
url = '{}/{}{}'.format(self.base_url, account_id, URL.PRODUCT)
return self.... |
def compileType(value):
if isinstance(value, Data):
ctype = 'Data'
elif isinstance(value, numbers.Integral):
ctype = 'int'
elif isinstance(value, numbers.Real):
ctype = 'double'
elif isinstance(value, numbers.Complex):
ctype = 'complex'
elif isinstance(value, str):
... |
class MBConv(nn.Module):
def __init__(self, w_in, exp_r, kernel, stride, se_r, w_out, bn_norm):
super(MBConv, self).__init__()
self.exp = None
w_exp = int((w_in * exp_r))
if (w_exp != w_in):
self.exp = nn.Conv2d(w_in, w_exp, 1, stride=1, padding=0, bias=False)
... |
class ConvBlock1bit(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation=1, groups=1, bias=False, bn_affine=True, activate=True, binarized=False):
super(ConvBlock1bit, self).__init__()
self.activate = activate
self.conv = Conv2d1bit(in_channels=in_... |
def flatten_state_dict(state_dict: dict) -> np.ndarray:
states = []
for (key, value) in state_dict.items():
if isinstance(value, dict):
state = flatten_state_dict(value)
if (state.size == 0):
state = None
elif isinstance(value, (tuple, list)):
... |
def split_at(iterable, pred, maxsplit=(- 1), keep_separator=False):
if (maxsplit == 0):
(yield list(iterable))
return
buf = []
it = iter(iterable)
for item in it:
if pred(item):
(yield buf)
if keep_separator:
(yield [item])
if (... |
def children(handle):
child_windows = []
def enum_child_proc(hwnd, lparam):
child_windows.append(hwnd)
return True
enum_child_proc_t = WINFUNCTYPE(c_int, wintypes.HWND, wintypes.LPARAM)
proc = enum_child_proc_t(enum_child_proc)
win32functions.EnumChildWindows(handle, proc, 0)
ret... |
def validate_all_op_level_dtype_bw_overrides(op_configs: OpTypeType, default_candidate: QuantDtypeBwInfo):
for (op_name, op_config) in op_configs.items():
if (ConfigDictKeys.SUPPORTED_KERNELS in op_config):
op_level_supported_kernels = op_config[ConfigDictKeys.SUPPORTED_KERNELS]
if c... |
class App_qt(App_base):
def __init__(self):
import types
(QtGui, QtCore) = self.importCoreAndGui()
(self._QtGui, self._QtCore) = (QtGui, QtCore)
if (not hasattr(QtGui, 'real_QApplication')):
QtGui.real_QApplication = QtGui.QApplication
class QApplication_hijacked(... |
class TestIndex(object):
def setup_method(self):
reload(pysat.instruments.pysat_testing)
self.name = 'testing'
self.ref_time = pysat.instruments.pysat_testing._test_dates['']['']
return
def teardown_method(self):
del self.ref_time, self.name
return
.parametriz... |
def read_cn_block(fid, pointer):
if ((pointer != 0) and (pointer is not None)):
temp = dict()
fid.seek(pointer)
(temp['BlockType'], temp['BlockSize'], temp['pointerToNextCNBlock'], temp['pointerToConversionFormula'], temp['pointerToCEBlock'], temp['pointerToCDBlock'], temp['pointerToChannelC... |
class FlagList(List):
combinable_values: Optional[Sequence] = None
_show_valtype = False
def __init__(self, *, none_ok: bool=False, completions: _Completions=None, valid_values: ValidValues=None, length: int=None) -> None:
super().__init__(valtype=String(), none_ok=none_ok, length=length, completion... |
def make_fast_generalized_attention(qkv_dim, renormalize_attention=True, numerical_stabilizer=0.0, nb_features=256, features_type='deterministic', kernel_fn=jax.nn.relu, kernel_epsilon=0.001, redraw_features=False, unidirectional=False, lax_scan_unroll=1):
logging.info('Fast generalized attention.: %s features and ... |
class SoundcloudLibrary(SongLibrary[(K, 'SoundcloudFile')]):
STAR = ['artist', 'title', 'genre', 'tags']
def __init__(self, client, player=None):
super().__init__('Soundcloud')
self.client = client
self._sids = [self.client.connect('songs-received', self._on_songs_received), self.client.... |
class LaneSection(XodrBase):
def __init__(self, s, centerlane):
super().__init__()
self.s = s
self.centerlane = centerlane
self.centerlane._set_lane_id(0)
self.leftlanes = []
self.rightlanes = []
self._left_id = 1
self._right_id = (- 1)
def __eq__(... |
class OptSimilarity_Albuterol(Molecule):
def _reward(self):
scorer = similarity(smiles='CC(C)(C)NCC(O)c1ccc(O)c(CO)c1', name='Albuterol', fp_type='FCFP4', threshold=0.75)
s_fn = scorer.wrapped_objective
molecule = Chem.MolFromSmiles(self._state)
if (molecule is None):
ret... |
.unit()
.parametrize('decorator', [pytask.mark.depends_on, pytask.mark.produces])
.parametrize(('values', 'expected'), [('a', ['a']), (['b'], [['b']]), (['e', 'f'], [['e', 'f']])])
def test_extract_args_from_mark(decorator, values, expected):
(values)
def task_example():
pass
parser = (depends_on if... |
class Effect8470(BaseEffect):
type = 'passive'
def handler(fit, container, context, projectionRange, **kwargs):
fit.drones.filteredItemBoost((lambda drone: drone.item.requiresSkill('Drones')), 'damageMultiplier', container.getModifiedItemAttr('capitalIndustrialCommandBonusDroneDamage'), skill='Capital I... |
def test_set_mixin(gl):
class M(SetMixin, FakeManager):
pass
url = '
responses.add(method=responses.PUT, url=url, json={'key': 'foo', 'value': 'bar'}, status=200, match=[responses.matchers.query_param_matcher({})])
mgr = M(gl)
obj = mgr.set('foo', 'bar')
assert isinstance(obj, FakeObject... |
class Discriminator(nn.Module):
def __init__(self, image_in_channels, edge_in_channels):
super(Discriminator, self).__init__()
self.texture_branch = TextureBranch(in_channels=image_in_channels)
self.structure_branch = StructureBranch(in_channels=edge_in_channels)
self.edge_detector =... |
class TempFile():
def __init__(self, suffix='.nc'):
self.filename = None
self.suffix = suffix
def __enter__(self):
(self.handle, self.filename) = tempfile.mkstemp(suffix=self.suffix)
os.close(self.handle)
return self.filename
def __exit__(self, *args):
os.remo... |
class TestChangeHosts(EndianTest):
def setUp(self):
self.req_args_0 = {'host': [183, 251, 198, 200], 'host_family': 0, 'mode': 0}
self.req_bin_0 = b'm\x00\x03\x00\x00\x00\x04\x00\xb7\xfb\xc6\xc8'
def testPackRequest0(self):
bin = request.ChangeHosts._request.to_binary(*(), **self.req_arg... |
class MyFormatter(argparse.RawTextHelpFormatter):
def add_argument(self, action):
if (action.help is not argparse.SUPPRESS):
get_invocation = self._format_action_invocation
invocations = [get_invocation(action)]
current_indent = self._current_indent
for subact... |
def get_default_smarts_object():
latitude = 40.4966
longitude = (- 3.462)
preasure_model = 1
altitude = 0.625
altura = 0.0
time_zone = 0
season = 'SUMMER'
albedo = 9
solar_position_mode = 3
atmospheric_data = 1
atmosphere_model = 'USSA'
precipitable_water = 0
ozone = ... |
class Model(nn.Module):
def __init__(self, args):
super().__init__()
self.leaky = 0.1
self.group_layers = nn.Sequential(nn.Conv2d(2, 32, 3, stride=1, padding=1, groups=2), nn.ReLU(inplace=True), nn.Conv2d(32, 64, 3, stride=1, padding=1, groups=2), nn.ReLU(inplace=True))
self.shared_l... |
class ReportGenerator():
def __init__(self, json_report):
self.json_report = json_report
rulegenerate_html_path = pkg_resources.resource_filename('quark.webreport', 'genrule_report_layout.html')
analysis_result_html_path = pkg_resources.resource_filename('quark.webreport', 'analysis_report_l... |
def sanitize_source(source):
match = re.match('^\\s*(C|CH|CHAN|CHANNEL)\\s*(?P<number>\\d)\\s*$|^\\s*(?P<name_only>MATH|LINE)\\s*$', source, re.IGNORECASE)
if match:
if (match.group('number') is not None):
source = ('C' + match.group('number'))
else:
source = match.group(... |
('/migrate_rooms', methods=['POST'])
_params([], need_username=True)
_wrapper_json
_web_opration_log('migrate_rooms', get_op_info=migrate_rooms_log)
def migrate_rooms(username):
json_data = request.get_json(force=True)
src_rooms = json_data.get('src_rooms', [])
dst_rooms = json_data.get('dst_rooms', [])
... |
def local_do_test(m):
if isinstance(m, type):
m = m.DUT()
m.elaborate()
m.apply(BehavioralRTLIRGenL2Pass(m))
m.apply(BehavioralRTLIRTypeCheckL2Pass(m))
try:
ref = m._rtlir_test_ref
for blk in m.get_update_blocks():
upblk = m.get_metadata(BehavioralRTLIRGenL2Pass.r... |
class KeystoneV3AuthTests(KeystoneAuthTestsMixin, unittest.TestCase):
def fake_keystone(self):
return fake_keystone(3, requires_email=True)
def emails(self):
return True
def test_query(self):
with self.fake_keystone() as keystone:
(response, federated_id, error_message) =... |
def get_device_class_from_sys_info(info: Dict[(str, Any)]) -> Type[SmartDevice]:
if (('system' not in info) or ('get_sysinfo' not in info['system'])):
raise SmartDeviceException("No 'system' or 'get_sysinfo' in response")
sysinfo: Dict[(str, Any)] = info['system']['get_sysinfo']
type_: Optional[str]... |
class Effect8013(BaseEffect):
runTime = 'early'
type = 'passive'
def handler(fit, implant, context, projectionRange, **kwargs):
fit.appliedImplants.filteredItemMultiply((lambda target: target.item.requiresSkill('Cybernetics')), 'shieldHpBonus', (implant.getModifiedItemAttr('ImplantSetNirvana') or 1)... |
class CB(nn.Module):
def __init__(self, nIn, nOut, kSize, stride=1):
super().__init__()
padding = int(((kSize - 1) / 2))
self.conv = nn.Conv2d(nIn, nOut, (kSize, kSize), stride=stride, padding=(padding, padding), bias=False)
self.bn = nn.BatchNorm2d(nOut, eps=0.001)
def forward(s... |
def build_lr_scheduler(optimizer: Optimizer, warmup_epochs: Union[(float, int)], epochs: int, num_lrs: int, train_data_size: int, batch_size: int, init_lr: float, max_lr: float, final_lr: float) -> Type[_LRScheduler]:
return NoamLR(optimizer=optimizer, warmup_epochs=[warmup_epochs], total_epochs=([epochs] * num_lrs... |
class FloorplanOptions():
tw1: float = 1.0
tw2: float = 1.0
tw3: float = 1.0
tw4: float = 1.0
tl1: float = 1.0
tl2: float = 1.0
tl3: float = 1.0
tl4: float = 1.0
type: FloorPlanType = FloorPlanType.RECTANGULAR
seed: int = 1
width: float = 4.0
length: float = 4.0
radiu... |
class ModelType(type):
def _check_abstract(self):
if (self.__table__ is None):
raise TypeError('GINO model {} is abstract, no table is defined.'.format(self.__name__))
def __iter__(self):
self._check_abstract()
return iter(self.__table__.columns)
def __getattr__(self, ite... |
def build_scheduler(cfg_sheduler, optimizer, model, logger):
lr_scheduler_cfg = cfg_sheduler['lr_scheduler']
lr_scheduler = build_lr_scheduler(optimizer=optimizer, lr=lr_scheduler_cfg['lr'], lr_clip=lr_scheduler_cfg['clip'], lr_decay_list=lr_scheduler_cfg['decay_list'], lr_decay_rate=lr_scheduler_cfg['decay_rat... |
def main():
parser = OptionParser()
parser.add_option('--maxage', dest='maxage', default='3600', help='Maximum age of information to use before re-running commands for this module', type='int')
(options, args) = parser.parse_args()
ops.survey.print_header('OS information')
lang_data = ops.system.sys... |
class TestSerializer(APITestCase, CassandraTestCase):
def test_serialize_creates(self):
now = datetime.now()
data = {'id': str(uuid.uuid4()), 'first_name': 'Homer', 'last_name': 'Simpson', 'is_real': True, 'favourite_number': 10, 'favourite_float_number': float(10.1), 'created_on': now}
seri... |
class AppliedSponsorshipNotificationToSponsorsTests(TestCase):
def setUp(self):
self.notification = notifications.AppliedSponsorshipNotificationToSponsors()
self.user = baker.make(settings.AUTH_USER_MODEL, email='')
self.verified_email = baker.make(EmailAddress, verified=True)
self.u... |
class Geodesic(object):
GEOGRAPHICLIB_GEODESIC_ORDER = 6
nA1_ = GEOGRAPHICLIB_GEODESIC_ORDER
nC1_ = GEOGRAPHICLIB_GEODESIC_ORDER
nC1p_ = GEOGRAPHICLIB_GEODESIC_ORDER
nA2_ = GEOGRAPHICLIB_GEODESIC_ORDER
nC2_ = GEOGRAPHICLIB_GEODESIC_ORDER
nA3_ = GEOGRAPHICLIB_GEODESIC_ORDER
nA3x_ = nA3_
... |
def unpack_inline_message_id(inline_message_id: str) -> 'raw.base.InputBotInlineMessageID':
padded = (inline_message_id + ('=' * ((- len(inline_message_id)) % 4)))
decoded = base64.urlsafe_b64decode(padded)
if (len(decoded) == 20):
unpacked = struct.unpack('<iqq', decoded)
return raw.types.I... |
def test_hamming_matrix():
answer = np.array([[0, 1, 1, 2, 1, 2, 2, 3], [1, 0, 2, 1, 2, 1, 3, 2], [1, 2, 0, 1, 2, 3, 1, 2], [2, 1, 1, 0, 3, 2, 2, 1], [1, 2, 2, 3, 0, 1, 1, 2], [2, 1, 3, 2, 1, 0, 2, 1], [2, 3, 1, 2, 1, 2, 0, 1], [3, 2, 2, 1, 2, 1, 1, 0]]).astype(float)
assert np.array_equal(distribution._hamming... |
def main():
if (not torch.cuda.is_available()):
logging.info('no gpu device available')
sys.exit(1)
np.random.seed(args.seed)
torch.cuda.set_device(args.gpu)
cudnn.benchmark = True
torch.manual_seed(args.seed)
cudnn.enabled = True
torch.cuda.manual_seed(args.seed)
logging... |
class Service(sb.Base, sasync.Async):
('Service', rus.optional((str, ru.Url)), rus.optional(ss.Session), rus.optional(sab.Base), rus.optional(dict), rus.optional(rus.one_of(SYNC, ASYNC, TASK)))
(rus.nothing)
def __init__(self, rm=None, session=None, _adaptor=None, _adaptor_state={}, _ttype=None):
tr... |
def make_some_widgets() -> List[Widget]:
widget_id = 0
widgets = []
for creator_id in range(3):
for kind in WidgetKind:
for has_knob in [True, False]:
for has_spinner in [True, False]:
derived = [w.widget_id for w in widgets[::(creator_id + 1)]]
... |
class OrganizationTest(TestCase):
def setUp(self):
pass
def test_createOrganization(self):
self.assertEqual(Organization.objects.count(), 0)
o = Organization.objects.create()
self.assertEqual(Organization.objects.count(), 1)
def test_org_autocreate_slug(self):
o = Org... |
class TestMessageSorting(unittest.TestCase):
def test_simple_sorting(self) -> None:
msgs = ['x.py:1: error: "int" not callable', 'foo/y.py:123: note: "X" not defined']
old_msgs = ['foo/y.py:12: note: "Y" not defined', 'x.py:8: error: "str" not callable']
assert (sort_messages_preserving_file... |
def test_download_and_cache_classifiers(monkeypatch, tmp_path):
responses.add(responses.GET, ' body='A\nB\nC')
def mock_get_cache_dir():
return tmp_path
monkeypatch.setattr(fv, 'get_cache_dir', mock_get_cache_dir)
classifiers = fv._download_and_cache_classifiers()
assert (classifiers == {'A'... |
def lookup_fully_qualified_typeinfo(modules: dict[(str, MypyFile)], name: str, *, allow_missing: bool) -> TypeInfo:
stnode = lookup_fully_qualified(name, modules, raise_on_missing=(not allow_missing))
node = (stnode.node if stnode else None)
if isinstance(node, TypeInfo):
return node
else:
... |
class _BaseUserscriptRunner(QObject):
got_cmd = pyqtSignal(str)
finished = pyqtSignal(guiprocess.GUIProcess)
def __init__(self, parent=None):
super().__init__(parent)
self._cleaned_up = False
self._filepath = None
self.proc = None
self._env: MutableMapping[(str, str)]... |
def test_pype_use_parent_context_swallow_stop_error(mock_pipe):
mocked_runner = mock_pipe.return_value.load_and_run_pipeline
mocked_runner.side_effect = Stop()
context = Context({'pype': {'name': 'pipe name', 'pipeArg': 'argument here', 'useParentContext': True, 'skipParse': True, 'raiseError': False}})
... |
def do_commit(new_ver, old_ver, dry_run, amend, ver_files):
import pathlib
cmt_msg = ('chore(ver): bump %s-->%s' % (old_ver, new_ver))
ver_files = [pathlib.Path(f).as_posix() for f in ver_files]
git_add = (['git', 'add'] + ver_files)
git_cmt = ['git', 'commit', '-m', cmt_msg]
if amend:
g... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--model_path', type=str, help='path where the pretrained model is stored.')
parser.add_argument('--data_root', type=str, default='data', help='path where the testing data is stored')
parser.add_argument('--rnn_type', type=str, default='... |
def define_template(title, page):
if (not page):
return
m = re.match('#REDIRECT.*?\\[\\[([^\\]]*)]]', page[0], re.IGNORECASE)
if m:
options.redirects[title] = m.group(1)
return
text = unescape(''.join(page))
text = comment.sub('', text)
text = reNoinclude.sub('', text)
... |
class CollaborativeCallback(transformers.TrainerCallback):
def __init__(self, dht: hivemind.DHT, optimizer: hivemind.CollaborativeOptimizer, model: torch.nn.Module, local_public_key: bytes, statistics_expiration: float):
super().__init__()
self.model = model
(self.dht, self.collaborative_opt... |
class PageQuestion(models.Model):
page = models.ForeignKey('Page', on_delete=models.CASCADE, related_name='page_questions')
question = models.ForeignKey('Question', on_delete=models.CASCADE, related_name='question_pages')
order = models.IntegerField(default=0)
class Meta():
ordering = ('page', '... |
class WAEnMMD(base_ae.SingleLatentWithPriorAE):
def __init__(self, encoder: BaseParameterisedDistribution, decoder: BaseParameterisedDistribution, latent_prior: BaseParameterisedDistribution, kernel: similarity_funcs.BaseSimilarityFunctions, c_function: similarity_funcs.SquaredEuclideanDistSimilarity()=None):
... |
class RubberbandItem(BaseItemMixin, QtWidgets.QGraphicsRectItem):
def __init__(self):
super().__init__()
color = QtGui.QColor(SELECT_COLOR)
color.setAlpha(40)
self.setBrush(QtGui.QBrush(color))
pen = QtGui.QPen(QtGui.QColor(0, 0, 0))
pen.setWidth(1)
pen.setCos... |
def gridsearch_var0(model, hessians, val_loader, ood_loader, interval, lam=1):
targets = torch.cat([y for (x, y) in val_loader], dim=0).float().cuda()
targets_out = (torch.ones_like(targets) * 0.5)
(vals, var0s) = ([], [])
pbar = tqdm(interval)
for var0 in pbar:
(mu, S) = estimate_variance(v... |
class BNAfterDynamicMatMul(torch.nn.Module):
def __init__(self, padding=0, stride=1, dilation=1, groups=1, bias=False):
super(BNAfterDynamicMatMul, self).__init__()
self.conv1d = torch.nn.Conv1d(10, 20, 3, padding=padding, stride=stride, dilation=dilation, groups=groups, bias=bias)
self.fc1 ... |
def __select_backend(backend: Optional[str], use_csc: bool):
if (backend is None):
return (piqp.SparseSolver() if use_csc else piqp.DenseSolver())
if (backend == 'dense'):
return piqp.DenseSolver()
if (backend == 'sparse'):
return piqp.SparseSolver()
raise ParamError(f'Unknown PI... |
class Vaihingen(Dataset):
NUM_CLASSES = 6
def __init__(self, args, base_dir=Path.db_root_dir('vaihingen'), split='train'):
super().__init__()
self._base_dir = base_dir
self._image_dir = os.path.join(self._base_dir, split, 'src')
self._cat_dir = os.path.join(self._base_dir, split,... |
class TestAllocColorCells(EndianTest):
def setUp(self):
self.req_args_0 = {'cmap': , 'colors': 45892, 'contiguous': 0, 'planes': 25420}
self.req_bin_0 = b'V\x00\x03\\xc2\xf3[D\xb3Lc'
self.reply_args_0 = {'masks': [, , ], 'pixels': [, , , , , , , , , , , , , , , , ], 'sequence_number': 34200}... |
class Metadata():
_raw: RawMetadata
def from_raw(cls, data: RawMetadata, *, validate: bool=True) -> 'Metadata':
ins = cls()
ins._raw = data.copy()
if validate:
exceptions: List[Exception] = []
try:
metadata_version = ins.metadata_version
... |
def extractor_maker(classifier):
def extractor(imgs):
import torch.nn.functional as F
x = imgs
x = F.relu(F.max_pool2d(classifier.conv1(x), 2))
x = F.relu(F.max_pool2d(classifier.conv2(x), 2))
x = x.view((- 1), 320)
x = F.relu(classifier.fc1(x))
x = x.view(img... |
class SimpleAverager(hivemind.DecentralizedAverager):
def __init__(self, trainer: Trainer, **kwargs):
self.trainer = trainer
initialize_optimizer_state(self.trainer.optimizer)
averaged_tensors = tuple((param.detach().cpu().float().clone() for param in self.trainer.model.parameters()))
... |
def codegen_module(kernel, device='cpu'):
adj = kernel.adj
forward_args = ['launch_bounds_t dim']
forward_params = ['dim']
for arg in adj.args:
forward_args.append(((arg.ctype() + ' var_') + arg.label))
forward_params.append(('var_' + arg.label))
reverse_args = [*forward_args]
re... |
_grad()
def generate_x_adv_denoised_v2(x, y, diffusion, model, classifier, pgd_conf, device, t):
net = Denoised_Classifier(diffusion, model, classifier, t)
delta = torch.zeros(x.shape).to(x.device)
loss_fn = torch.nn.CrossEntropyLoss(reduction='sum')
eps = pgd_conf['eps']
alpha = pgd_conf['alpha']
... |
def loss_coteaching_plus(logits, logits2, labels, forget_rate, ind, noise_or_not, step):
outputs = F.softmax(logits, dim=1)
outputs2 = F.softmax(logits2, dim=1)
(_, pred1) = torch.max(logits.data, 1)
(_, pred2) = torch.max(logits2.data, 1)
(pred1, pred2) = (pred1.cpu().numpy(), pred2.cpu().numpy())
... |
class CIFAR10MSDNet(nn.Module):
def __init__(self, channels, init_layer_channels, num_feature_blocks, use_bottleneck, bottleneck_factors, in_channels=3, in_size=(32, 32), num_classes=10):
super(CIFAR10MSDNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self... |
.django_db
def test_create_user_with_extra_fields():
user = User.objects.create_user('', 'johnpassword', name='John', full_name='John Lennon', gender='male', date_birth=datetime.datetime.strptime('09/10/1940', '%d/%m/%Y'))
assert (user.name == 'John')
assert (user.full_name == 'John Lennon')
assert (use... |
def test_vertical_perspective_operation__defaults():
aeaop = VerticalPerspectiveConversion(viewpoint_height=10)
assert (aeaop.name == 'unknown')
assert (aeaop.method_name == 'Vertical Perspective')
assert (_to_dict(aeaop) == {'Latitude of topocentric origin': 0.0, 'Longitude of topocentric origin': 0.0,... |
class TestAdaroundOptimizer():
.skipif((not torch.cuda.is_available()), reason='This unit-test is meant to be run on GPU')
.parametrize('warm_start', [1.0, 0.2])
def test_optimize_rounding(self, warm_start):
if (version.parse(torch.__version__) >= version.parse('1.13')):
np.random.seed(0... |
def test_add_nodes_inbetween_branches():
(a, b, c, d, e, f, x, y) = get_pseudo_nodes(8)
g = Graph()
c0 = ((g.orphan() >> a) >> b)
c1 = ((g.orphan() >> x) >> y)
c2 = (((c0 >> c) >> d) >> c1)
c3 = (((c0 >> e) >> f) >> c1)
assert (c0.range == g.indexes_of(a, b, _type=tuple))
assert (c1.rang... |
class BatchSampler(BaseSampler):
def __init__(self, algo):
self.algo = algo
super(BatchSampler, self).__init__(algo)
def start_worker(self):
parallel_sampler.populate_task(self.algo.env, self.algo.policy, scope=self.algo.scope)
def shutdown_worker(self):
parallel_sampler.term... |
_tokenizers
_pandas
class LayoutLMv3TokenizationTest(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = LayoutLMv3Tokenizer
rust_tokenizer_class = LayoutLMv3TokenizerFast
test_rust_tokenizer = True
space_between_special_tokens = False
test_seq2seq = False
from_pretrained_kwargs = {'cls_... |
def test_apply_text_edits_multiline(pylsp):
pylsp.workspace.put_document(DOC_URI, '0\n1\n2\n3\n4')
test_doc = pylsp.workspace.get_document(DOC_URI)
assert (apply_text_edits(test_doc, [{'range': {'start': {'line': 2, 'character': 0}, 'end': {'line': 3, 'character': 0}}, 'newText': 'Hello'}, {'range': {'start... |
class metric_manager(object):
def __init__(self, save_dir, model, dic_eval_trial, save_best_only=True):
self.save_dir = save_dir
self.model = model
self.save_best_only = save_best_only
self.best_eer = {}
self.best_min_dcf = {}
for key in dic_eval_trial.keys():
... |
def test_multi_marker_union_with_union_multi_is_single_marker() -> None:
m = parse_marker('sys_platform == "darwin" and python_version == "3"')
m2 = parse_marker('sys_platform == "darwin" and (python_version < "3" or python_version > "3")')
assert (str(m.union(m2)) == 'sys_platform == "darwin"')
assert ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.