code stringlengths 281 23.7M |
|---|
class XHKGExchangeCalendar(TradingCalendar):
name = 'XHKG'
tz = timezone('Asia/Hong_Kong')
open_times = ((None, time(10, 1)), (pd.Timestamp('2011-03-07'), time(9, 31)))
break_start_times = ((None, time(12, 1)),)
break_end_times = ((None, time(13, 0)),)
close_times = ((None, time(16)),)
regul... |
def adjust_lr(optimizer, epoch, eta_max=args.init_lr, eta_min=0.0):
cur_lr = 0.0
if (args.lr_type == 'SGDR'):
i = int(math.log2(((epoch / args.sgdr_t) + 1)))
T_cur = (epoch - (args.sgdr_t * ((2 ** i) - 1)))
T_i = (args.sgdr_t * (2 ** i))
cur_lr = (eta_min + ((0.5 * (eta_max - eta... |
_api()
class filter(Stream):
def __init__(self, upstream, predicate, *args, **kwargs):
if (predicate is None):
predicate = _truthy
self.predicate = predicate
stream_name = kwargs.pop('stream_name', None)
self.kwargs = kwargs
self.args = args
Stream.__init_... |
.skipif((os.name == 'nt'), reason='Fails on Windows')
def test_workspace_loads_pycodestyle_config(pylsp, tmpdir):
workspace1_dir = tmpdir.mkdir('Test123')
pylsp.root_uri = str(workspace1_dir)
pylsp.workspace._root_uri = str(workspace1_dir)
workspace2_dir = tmpdir.mkdir('NewTest456')
cfg = workspace2... |
class TestViiL2NCFileHandler(unittest.TestCase):
def setUp(self):
self.test_file_name = ((TEST_FILE + str(uuid.uuid1())) + '.nc')
with Dataset(self.test_file_name, 'w') as nc:
g1 = nc.createGroup('data')
g1.createDimension('num_pixels', 100)
g1.createDimension('nu... |
class EditableModulePureFunction(PureFunction):
def __init__(self, obj: EditableModule, method: Callable):
self.obj = obj
self.method = method
super().__init__(method)
def _get_all_obj_params_init(self) -> List:
return list(self.obj.getparams(self.method.__name__))
def _set_a... |
def migrate_old_content(apps, schema_editor):
Release = apps.get_model('downloads', 'Release')
db_alias = schema_editor.connection.alias
releases = Release.objects.using(db_alias).filter(release_page__isnull=False)
for release in releases:
content = '\n'.join(release.release_page.content.raw.spl... |
def get_name_params_difference(named_parameters1, named_parameters2):
common_names = list(set(named_parameters1.keys()).intersection(set(named_parameters2.keys())))
named_diff_parameters = {}
for key in common_names:
named_diff_parameters[key] = get_diff_weights(named_parameters1[key], named_paramet... |
def test_curried_operator():
import operator
for (k, v) in vars(cop).items():
if (not callable(v)):
continue
if (not isinstance(v, toolz.curry)):
try:
v(1)
except TypeError:
try:
v('x')
except... |
def nature_cnn(unscaled_images, **conv_kwargs):
scaled_images = (tf.cast(unscaled_images, tf.float32) / 255.0)
activ = tf.nn.relu
h = activ(conv(scaled_images, 'c1', nf=32, rf=8, stride=4, init_scale=np.sqrt(2), **conv_kwargs))
h2 = activ(conv(h, 'c2', nf=64, rf=4, stride=2, init_scale=np.sqrt(2), **con... |
class AMPServerFactory(protocol.ServerFactory):
noisy = False
def logPrefix(self):
return 'AMP'
def __init__(self, portal):
self.portal = portal
self.protocol = AMPServerProtocol
self.broadcasts = []
self.server_connection = None
self.launcher_connection = Non... |
def download_gif_file(gif_id: str, download_url: str, gif_dir: str):
gif_filepath = gif_id_to_filepath(gif_id, gif_dir=gif_dir)
Path(os.path.dirname(gif_filepath)).mkdir(parents=True, exist_ok=True)
if os.path.exists(gif_filepath):
return gif_filepath
try:
img_file = requests.get(downloa... |
class RemoveColumnsCollator():
def __init__(self, data_collator, signature_columns, logger=None, model_name: Optional[str]=None, description: Optional[str]=None):
self.data_collator = data_collator
self.signature_columns = signature_columns
self.logger = logger
self.description = des... |
def _sort_albums(songs):
no_album_count = 0
albums = {}
for song in songs:
if ('album' in song):
albums[song.list('album')[0]] = song
else:
no_album_count += 1
albums = [(song.get('date', ''), song, album) for (album, song) in albums.items()]
albums.sort()
... |
def extract_classes(chunks: Iterable[CacheData]) -> Iterable[JsonDict]:
def extract(chunks: Iterable[JsonDict]) -> Iterable[JsonDict]:
for chunk in chunks:
if isinstance(chunk, dict):
(yield chunk)
(yield from extract(chunk.values()))
elif isinstance(c... |
def _filter_gabriel(edges, coordinates):
edge_pointer = 0
n_edges = len(edges)
to_drop = []
while (edge_pointer < n_edges):
edge = edges[edge_pointer]
cardinality = 0
for joff in range(edge_pointer, n_edges):
next_edge = edges[joff]
if (next_edge[0] != edg... |
class Animation(pg.ItemGroup):
def __init__(self, sim):
pg.ItemGroup.__init__(self)
self.sim = sim
self.clocks = sim.clocks
self.items = {}
for (name, cl) in self.clocks.items():
item = ClockItem(cl)
self.addItem(item)
self.items[name] = it... |
def resolve_func_args(test_func, posargs, kwargs):
sig = inspect.signature(test_func)
assert (list(iter(sig.parameters))[0] == 'self')
posargs.insert(0, SelfMarker)
ba = sig.bind(*posargs, **kwargs)
ba.apply_defaults()
args = ba.arguments
required_args = [n for (n, v) in sig.parameters.items... |
def test_create_beam_configuration_description_vanilla():
default_config = BeamConfiguration(power=BeamAmmoConfiguration(0, (- 1), (- 1), 0, 0, 5, 0), dark=BeamAmmoConfiguration(1, 45, (- 1), 1, 5, 5, 30), light=BeamAmmoConfiguration(2, 46, (- 1), 1, 5, 5, 30), annihilator=BeamAmmoConfiguration(3, 46, 45, 1, 5, 5, ... |
class Bear(Creature):
def __init__(self, rand):
super().__init__(rand)
self.attack = [1, 10]
self.hp_max = 20
self.hp = self.hp_max
self.love = 3
self.name = 'Bear'
self.images = ['bear_normal']
def turn(self):
dmg = self.rand.randint(*self.attack)... |
class TrickUsagePopup(QtWidgets.QDialog, Ui_TrickUsagePopup):
def __init__(self, parent: QWidget, window_manager: WindowManager, preset: Preset):
super().__init__(parent)
self.setupUi(self)
set_default_window_icon(self)
self._window_manager = window_manager
self._game_descrip... |
def group_channels(nuts):
by_ansl = {}
for nut in nuts:
if (nut.kind_id != CHANNEL):
continue
ansl = nut.codes[:4]
if (ansl not in by_ansl):
by_ansl[ansl] = {}
group = by_ansl[ansl]
k = (nut.codes[4][:(- 1)], nut.deltat, nut.tmin, nut.tmax)
... |
def test_filerewriter_is_str_dir_windows(windows):
assert (filesystem.FileRewriter.is_str_dir(Path('blah\\')) is False)
assert (filesystem.FileRewriter.is_str_dir('/blah') is False)
assert (filesystem.FileRewriter.is_str_dir('/blah/') is True)
assert (filesystem.FileRewriter.is_str_dir('c:\\blah\\') is ... |
def recover_params(param_groups, param_names, rank=None, neighbor_hat_params=None, get_hat_params=True):
(params, _) = get_data(param_groups, param_names, is_get_grad=False)
flatten_params = TensorBuffer(params)
if get_hat_params:
assert ((neighbor_hat_params is not None) and (rank is not None))
... |
def construct_infobox_prompt(current_sentence, current_name, other_names, num_examples=5, random_order=False):
instruction = 'Extract attributes from the given context using the format Attribute: Value.\n----'
example_library = get_example_library()
current_encoding = sentence_encode([current_sentence])
... |
class Tee():
def __init__(self, fname, mode='a'):
self.stdout = sys.stdout
self.file = open(fname, mode)
def write(self, message):
self.stdout.write(message)
self.file.write(message)
self.flush()
def flush(self):
self.stdout.flush()
self.file.flush() |
def wide_resnet101_2d(deconv, delinear, channel_deconv, pretrained=False, progress=True, **kwargs):
kwargs['width_per_group'] = (64 * 2)
return _resnet('wide_resnet101_2', Bottleneck, [3, 4, 23, 3], pretrained, progress, deconv=deconv, delinear=delinear, channel_deconv=channel_deconv, **kwargs) |
class sysctl_oid_t(ctypes.Structure):
class slist_entry(ctypes.Structure):
_fields_ = (('sle_next', POINTER64),)
_fields_ = (('oid_parent', POINTER64), ('oid_link', slist_entry), ('oid_number', ctypes.c_int32), ('oid_kind', ctypes.c_int32), ('oid_arg1', POINTER64), ('oid_arg2', ctypes.c_int32), ('oid_na... |
def test_licenses():
assert isinstance(LICENSES, dict)
assert (list(LICENSES) == sorted(LICENSES))
for (name, data) in LICENSES.items():
assert isinstance(data, dict)
assert ('id' in data)
assert isinstance(data['id'], str)
assert (data['id'].lower() == name)
assert (... |
def test_ae_higherresolution_head():
with pytest.raises(AssertionError):
_ = AEHigherResolutionHead(in_channels=512, num_joints=17, with_ae_loss=[True, False], extra={'final_conv_kernel': 0}, loss_keypoint=dict(type='MultiLossFactory', num_joints=17, num_stages=2, ae_loss_type='exp', with_ae_loss=[True, Fal... |
class TestValidator(SetUpTest, TestCase):
def test_validator_should_succeed(self):
with open(self.qlr_file) as f:
self.assertTrue(validator(f))
def test_validator_should_failed(self):
tf = NamedTemporaryFile(mode='w+t', suffix='.qlr')
tf.write('<!DOCTYPE qgis-layer-definition... |
def convert_conv_fc(blobs, state_dict, caffe_name, torch_name, converted_names):
state_dict[(torch_name + '.weight')] = torch.from_numpy(blobs[(caffe_name + '_w')])
converted_names.add((caffe_name + '_w'))
if ((caffe_name + '_b') in blobs):
state_dict[(torch_name + '.bias')] = torch.from_numpy(blobs... |
def translate_pattern(pattern, anchor=1, prefix=None, is_regex=0):
if is_regex:
if isinstance(pattern, str):
return re.compile(pattern)
else:
return pattern
(start, _, end) = glob_to_re('_').partition('_')
if pattern:
pattern_re = glob_to_re(pattern)
a... |
class Migration(migrations.Migration):
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('grants', '0010_remove_grant_user_id_grant_user')]
operations = [migrations.AlterField(model_name='grant', name='user', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.del... |
def main(memo, env, road_net, gui, volume, suffix, mod, cnt, gen, r_all, workers, onemodel):
NUM_COL = int(road_net.split('_')[0])
NUM_ROW = int(road_net.split('_')[1])
num_intersections = (NUM_ROW * NUM_COL)
print('num_intersections:', num_intersections)
ENVIRONMENT = ['sumo', 'anon'][env]
if r... |
class TestPassportElementErrorSelfieWithoutRequest(TestPassportElementErrorSelfieBase):
def test_slot_behaviour(self, passport_element_error_selfie):
inst = passport_element_error_selfie
for attr in inst.__slots__:
assert (getattr(inst, attr, 'err') != 'err'), f"got extra slot '{attr}'"
... |
class StorageAssets(models.Model):
storage_types = ((0, ''), (1, ''), (2, ''), (3, ''), (4, ''))
assets = models.OneToOneField('Assets', on_delete=models.CASCADE)
storage_type = models.SmallIntegerField(choices=storage_types, default=0, verbose_name='')
class Meta():
db_table = 'ops_storage_asse... |
def test_available_commands(bot):
('test1', order=10)
def test1():
pass
('test2')
def test2():
pass
('test3', hidden=True)
def test3():
pass
assert ([cmd.name for cmd in bot.available_commands()] == ['help', 'test2', 'test1'])
assert ([cmd.name for cmd in bot.avai... |
class TestArrayColumns(BaseTestColumns):
def test_ArrayColumnInt64(self) -> None:
data = [None, [], [1], [1, None, 2], None]
col = infer_column(data)
self.assert_Column(col.elements(), [1, 1, None, 2])
for (sliced_col, sliced_data) in ((col, data), (col.slice(2, 2), data[2:4]), (col.... |
def test_arrayToLineSegments():
xy = np.array([0.0])
parray = arrayToLineSegments(xy, xy, connect='all', finiteCheck=True)
segs = parray.drawargs()
assert (isinstance(segs, tuple) and (len(segs) in [1, 2]))
if (len(segs) == 1):
assert (len(segs[0]) == 0)
elif (len(segs) == 2):
as... |
def metadata_and_status(status):
return MockMessage(body=('', {'Metadata': obj({'mpris:trackid': obj(1), 'xesam:url': obj('/path/to/rickroll.mp3'), 'xesam:title': obj('Never Gonna Give You Up'), 'xesam:artist': obj(['Rick Astley']), 'xesam:album': obj('Whenever You Need Somebody'), 'mpris:length': obj()}), 'Playbac... |
class Migration(migrations.Migration):
dependencies = [('tasks', '0029_sites_blank')]
operations = [migrations.AddField(model_name='task', name='available', field=models.BooleanField(default=True, help_text='Designates whether this task is generally available for projects.', verbose_name='Available'))] |
class SetExtentToLocation(QtWidgets.QWidget):
def __init__(self, *args, m=None, **kwargs):
super().__init__(*args, **kwargs)
self.m = m
label = QtWidgets.QLabel('<b>Query Location:</b>')
self.inp = QtWidgets.QLineEdit()
self.inp.returnPressed.connect(self.set_extent)
... |
class PayToEdit(CompletionTextEdit, ScanQRTextEdit, Logger):
def __init__(self, win: 'ElectrumWindow'):
CompletionTextEdit.__init__(self)
ScanQRTextEdit.__init__(self, config=win.config)
Logger.__init__(self)
self.win = win
self.amount_edit = win.amount_e
self.setFont... |
def inv_z_basis_gate(pauli: str) -> cirq.Gate:
if ((pauli == 'I') or (pauli == 'Z')):
return cirq.I
if (pauli == 'X'):
return cirq.H
if (pauli == 'Y'):
return cirq.PhasedXZGate(axis_phase_exponent=(- 0.5), x_exponent=0.5, z_exponent=(- 0.5))
raise ValueError('Invalid Pauli.') |
_hook('tensorboard_plot')
class TensorboardPlotHook(ClassyHook):
on_end = ClassyHook._noop
def __init__(self, tb_writer, log_period: int=10) -> None:
super().__init__()
if (not tb_available):
raise ModuleNotFoundError('tensorboard not installed, cannot use TensorboardPlotHook')
... |
class Config(object):
rule_base_sys_nlu = '/home/wyshi/simulator/simulator/nlu_model/model/model-test-30-new.pkl'
use_sl_simulator = True
use_sl_generative = False
INTERACTIVE = True
device = 'cpu'
use_gpu = False
nlg_sample = False
nlg_template = True
n_episodes = 30000
save_dir... |
class Mask(rq.List):
def __init__(self, name):
rq.List.__init__(self, name, rq.Card32, pad=0)
def pack_value(self, val):
mask_seq = array.array(rq.struct_to_array_codes['L'])
if isinstance(val, integer_types):
if (sys.byteorder == 'little'):
def fun(val):
... |
class Transform(torch.nn.Module):
def __init__(self, image_size):
super().__init__()
self.transforms = torch.nn.Sequential(Resize([image_size], interpolation=InterpolationMode.BICUBIC), CenterCrop(image_size), ConvertImageDtype(torch.float), Normalize((0., 0.4578275, 0.), (0., 0., 0.)))
def forw... |
class CompactnessWeightedAxis():
def __init__(self, gdf, areas=None, perimeters=None, longest_axis=None):
self.gdf = gdf
gdf = gdf.copy()
if (perimeters is None):
gdf['mm_p'] = gdf.geometry.length
perimeters = 'mm_p'
elif (not isinstance(perimeters, str)):
... |
_default_transform.register(BoundedContinuous)
def bounded_cont_transform(op, rv, bound_args_indices=None):
if (bound_args_indices is None):
raise ValueError(f'Must specify bound_args_indices for {op} bounded distribution')
def transform_params(*args):
(lower, upper) = (None, None)
if (b... |
class PrefetchDataset(torch.utils.data.Dataset):
def __init__(self, opt, dataset, pre_process_func):
self.images = dataset.images
self.load_image_func = dataset.coco.loadImgs
self.img_dir = dataset.img_dir
self.pre_process_func = pre_process_func
self.get_default_calib = data... |
class _torchxconfig(Action):
_subcmd_configs: Dict[(str, Dict[(str, str)])] = {}
def __init__(self, subcmd: str, dest: str, option_strings: Sequence[Text], required: bool=False, default: Any=None, **kwargs: Any) -> None:
cfg = self._subcmd_configs.setdefault(subcmd, config.get_configs(prefix='cli', name... |
def ToTimeStr(val):
val = Decimal(val)
if (val >= ):
return '{} s'.format((val / ).quantize(Decimal('0.')))
if (val >= 1000000):
return '{} ms'.format((val / 1000000).quantize(Decimal('0.000001')))
if (val >= 1000):
return '{} us'.format((val / 1000).quantize(Decimal('0.001')))
... |
def imagesc(img, title=None, experiment=None, step=None, scale='minmax'):
if (scale == 'minmax'):
img = (img - img.ravel().min())
img = (img / img.ravel().max())
elif ((type(scale) is float) or (type(scale) is int)):
img = (((img * 0.5) / scale) + 0.5)
elif ((type(scale) is list) or ... |
class Shard(Enum):
PC_AS = 'pc-as'
PC_EU = 'pc-eu'
PC_KAKAO = 'pc-kakao'
PC_KRJP = 'pc-krjp'
PC_NA = 'pc-na'
PC_OC = 'pc-oc'
PC_SA = 'pc-sa'
PC_SEA = 'pc-sea'
PC_JP = 'pc-jp'
PC_RU = 'pc-ru'
PC_TOURNAMENT = 'pc-tournament'
XBOX_AS = 'xbox-as'
XBOX_EU = 'xbox-eu'
X... |
def test_tmp_path_too_long_on_parametrization(pytester: Pytester) -> None:
pytester.makepyfile('\n import pytest\n .parametrize("arg", ["1"*1000])\n def test_some(arg, tmp_path):\n tmp_path.joinpath("hello").touch()\n ')
reprec = pytester.inline_run()
reprec.assertoutcome(... |
class Reshape(Layer):
def __init__(self, target_shape, **kwargs):
super(Reshape, self).__init__(**kwargs)
self.target_shape = tuple(target_shape)
def _fix_unknown_dimension(self, input_shape, output_shape):
output_shape = list(output_shape)
msg = 'total size of new array must be ... |
def run_experiment(variant):
tf.logging.set_verbosity(tf.logging.INFO)
with tf.Session() as sess:
data = joblib.load(variant['snapshot_filename'])
policy = data['policy']
env = data['env']
num_skills = (data['policy'].observation_space.flat_dim - data['env'].spec.observation_spac... |
def get_current_samples_dir():
if ('pyglet_mp_samples_dir' not in os.environ):
raise mpexceptions.ExceptionUndefinedSamplesDir()
path = os.environ['pyglet_mp_samples_dir']
if (not os.path.isdir(path)):
raise mpexceptions.ExceptionSamplesDirDoesNotExist(path)
return path |
def distributed_init(args):
if (not getattr(args, 'tpu', False)):
if torch.distributed.is_initialized():
warnings.warn('Distributed is already initialized, cannot initialize twice!')
else:
logger.info('distributed init (rank {}): {}'.format(args.distributed_rank, args.distrib... |
class CachingImageList(wx.ImageList):
def __init__(self, width, height):
wx.ImageList.__init__(self, width, height)
self.map = {}
def GetImageIndex(self, *loaderArgs):
id_ = self.map.get(loaderArgs)
if (id_ is None):
bitmap = BitmapLoader.getBitmap(*loaderArgs)
... |
def load_callbacks(output_dir):
output_dir = Path(output_dir)
output_dir.mkdir(exist_ok=True, parents=True)
(output_dir / 'ckpts').mkdir(exist_ok=True, parents=True)
callbacks = []
callbacks.append(ModelCheckpoint(monitor='val_mae_max_metric', dirpath=str((output_dir / 'ckpts')), filename='{epoch:02... |
class KickstartParser(object):
def __init__(self, handler, followIncludes=True, errorsAreFatal=True, missingIncludeIsFatal=True, unknownSectionIsFatal=True):
self.errorsAreFatal = errorsAreFatal
self.errorsCount = 0
self.followIncludes = followIncludes
self.handler = handler
... |
class BatchTrainer(Trainer):
def build_data(self, split):
if ((split == TRAIN_SPLIT) and (self.eval_split != TRAIN_SPLIT)):
return self.build_batch(split)
elif (split in (TRAIN_SPLIT, VALID_SPLIT, TEST_SPLIT)):
return self.build_episode(split)
else:
raise ... |
class Effect5424(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Large Hybrid Turret')), 'speed', ship.getModifiedItemAttr('shipBonusGB'), skill='Gallente Battleship', **kwargs) |
class SendSubmissionErrors(BaseErrorType):
class _SendSubmissionErrors():
instance: list[str] = strawberry.field(default_factory=list)
title: list[str] = strawberry.field(default_factory=list)
abstract: list[str] = strawberry.field(default_factory=list)
topic: list[str] = strawberry.... |
def _msvc14_find_vc2015():
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\VisualStudio\\SxS\\VC7', 0, (winreg.KEY_READ | winreg.KEY_WOW64_32KEY))
except OSError:
return (None, None)
best_version = 0
best_dir = None
with key:
for i in itertools.coun... |
class TestDeprecated():
_type_check
def test_deprecated(self, monkeypatch):
mod = types.ModuleType('TestDeprecated/test_deprecated')
monkeypatch.setitem(sys.modules, mod.__name__, mod)
deprecated(name='X', value=1, module_name=mod.__name__, message='deprecated message text', warning_clas... |
_ordering
class APEBinaryValue(_APEValue):
kind = BINARY
def _parse(self, data):
self.value = data
def _write(self):
return self.value
def _validate(self, value):
if (not isinstance(value, bytes)):
raise TypeError('value not bytes')
return bytes(value)
def... |
class MyBertForTokenClassification(BertPreTrainedModel):
def __init__(self, config, num_labels):
super(MyBertForTokenClassification, self).__init__(config)
self.num_labels = num_labels
self.bert = BertModel(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.cl... |
def parse_args():
parser = argparse.ArgumentParser(description='Train a recognizer')
parser.add_argument('config', help='train config file path')
parser.add_argument('--work-dir', help='the dir to save logs and models')
parser.add_argument('--resume-from', help='the checkpoint file to resume from')
... |
class StubgencSuite(unittest.TestCase):
def test_infer_hash_sig(self) -> None:
assert_equal(infer_c_method_args('__hash__'), [self_arg])
assert_equal(infer_method_ret_type('__hash__'), 'int')
def test_infer_getitem_sig(self) -> None:
assert_equal(infer_c_method_args('__getitem__'), [self... |
def load_pairs(raw_data, split, direction):
(src, tgt) = direction.split('-')
src_f = f'{raw_data}/{split}.{direction}.{src}'
tgt_f = f'{raw_data}/{split}.{direction}.{tgt}'
if (tgt != 'en_XX'):
(src_f, tgt_f) = (tgt_f, src_f)
if (os.path.exists(src_f) and os.path.exists(tgt_f)):
ret... |
def repo_with_git_flow_and_release_channels_angular_commits(git_repo_factory, file_in_repo):
git_repo = git_repo_factory()
add_text_to_file(git_repo, file_in_repo)
git_repo.git.commit(m='Initial commit')
add_text_to_file(git_repo, file_in_repo)
git_repo.git.commit(m=COMMIT_MESSAGE.format(version='0.... |
def initial_data(watch_html: str) -> str:
patterns = ['window\\[[\'\\"]ytInitialData[\'\\"]]\\s*=\\s*', 'ytInitialData\\s*=\\s*']
for pattern in patterns:
try:
return parse_for_object(watch_html, pattern)
except HTMLParseError:
pass
raise RegexMatchError(caller='initi... |
def conv_block(x, growth_rate, name, params=PARAM_NONE):
bn_axis = (3 if (backend.image_data_format() == 'channels_last') else 1)
x1 = layers.BatchNormalization(axis=bn_axis, epsilon=BN_EPS, name=(name + '_0_bn'))(x, params=params)
x1 = layers.Activation('relu', name=(name + '_0_relu'))(x1)
x1 = layers.... |
class TestFastConsumerFactory():
('confluent_kafka.Consumer')
def test_make_kafka_consumer(self, kafka_consumer, name, baseplate, bootstrap_servers, group_id, topics):
mock_consumer = mock.Mock()
mock_consumer.list_topics.return_value = mock.Mock(topics={'topic_1': mock.Mock(), 'topic_2': mock.M... |
def assert_soquets_belong_to_registers(cbloq: CompositeBloq):
for soq in cbloq.all_soquets:
reg = soq.reg
if (len(soq.idx) != len(reg.shape)):
raise BloqError(f'{soq} has an idx of the wrong shape for {reg}')
for (soq_i, reg_max) in zip(soq.idx, reg.shape):
if (soq_i ... |
class WinFontLoader(_FontLoader):
localFontRegPath = None
def getLocalFontRegPath(cls):
if (cls.localFontRegPath is not None):
return cls.localFontRegPath
import winreg
home = os.path.expanduser('~')
localFontPath = '\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\... |
def configure(config_object, testing=False):
logger.debug('Configuring database')
db_kwargs = dict(config_object['DB_CONNECTION_ARGS'])
write_db_uri = config_object['DB_URI']
db.initialize(_db_from_url(write_db_uri, db_kwargs))
parsed_write_uri = make_url(write_db_uri)
db_random_func.initialize(... |
class ConditionRendererMixin():
def render_condition(self, xml, condition):
if (condition['uri'] not in self.uris):
self.uris.add(condition['uri'])
xml.startElement('condition', {'dc:uri': condition['uri']})
self.render_text_element(xml, 'uri_prefix', {}, condition['uri_p... |
def test_set_client_cert_unsuccessful_multiple_values(tester: CommandTester, mocker: MockerFixture) -> None:
mocker.spy(ConfigSource, '__init__')
with pytest.raises(ValueError) as e:
tester.execute('certificates.foo.client-cert path/to/cert.pem path/to/cert.pem')
assert (str(e.value) == 'You must pa... |
class CmdPy(COMMAND_DEFAULT_CLASS):
key = 'py'
aliases = ['!']
switch_options = ('time', 'edit', 'clientraw')
locks = 'cmd:perm(py) or perm(Developer)'
help_category = 'System'
def func(self):
caller = self.caller
pycode = self.args
if ('edit' in self.switches):
... |
def test_installer_file_contains_valid_version(default_installation: Path) -> None:
installer_file = ((default_installation / 'demo-0.1.0.dist-info') / 'INSTALLER')
with open(installer_file) as f:
installer_content = f.read()
match = re.match('Poetry (?P<version>.*)', installer_content)
assert m... |
.parametrize('fixer, in_file', collect_all_test_fixtures(), ids=_get_id)
def test_check_fixture(in_file, fixer, tmpdir):
if fixer:
main('unittest2pytest.fixes', args=['--no-diffs', '--fix', fixer, '-w', in_file, '--nobackups', '--output-dir', str(tmpdir)])
else:
main('unittest2pytest.fixes', arg... |
class TestDownsampledRowwiseOperation(WithAssetFinder, ZiplineTestCase):
T = partial(pd.Timestamp, tz='utc')
START_DATE = T('2014-01-01')
END_DATE = T('2014-02-01')
HALF_WAY_POINT = T('2014-01-15')
dates = pd.date_range(START_DATE, END_DATE)
ASSET_FINDER_COUNTRY_CODE = '??'
class SidFactor(C... |
def test_metadata_with_wildcard_dependency_constraint() -> None:
test_path = ((Path(__file__).parent / 'fixtures') / 'with_wildcard_dependency_constraint')
builder = Builder(Factory().create_poetry(test_path))
metadata = Parser().parsestr(builder.get_metadata_content())
requires = metadata.get_all('Requ... |
class VelocityDiscriminator(Discriminator):
def __init__(self, input_dim):
super(VelocityDiscriminator, self).__init__(input_dim=input_dim)
self.make_network(dim_input=input_dim, dim_output=2)
self.init_tf()
def make_network(self, dim_input, dim_output):
n_mlp_layers = 4
... |
def test_resnet_bottleneck():
with pytest.raises(AssertionError):
Bottleneck(64, 64, style='tensorflow')
with pytest.raises(AssertionError):
plugins = [dict(cfg=dict(type='ContextBlock', ratio=(1.0 / 16)), position='after_conv4')]
Bottleneck(64, 16, plugins=plugins)
with pytest.raise... |
class Predictor(BasePredictor):
def setup(self):
self.device = 'cuda'
self.netEC = ContentEncoder()
self.netEC.eval()
self.netG = Generator()
self.netG.eval()
self.sampler = ICPTrainer(np.empty([0, 256]), 128)
def predict(self, task: str=Input(choices=TASKS, defau... |
def update_figure(iframe, *args):
print(('Updating figure! (frame %03d)' % iframe))
okada.depth = depths[iframe]
okada.strike = strikes[iframe]
sandbox.processSources()
for (im, comp) in zip(images, components):
args = imargs(comp)
im.set_data(comp)
return images |
def register_all_lvis(root):
for (dataset_name, splits_per_dataset) in _PREDEFINED_SPLITS_LVIS.items():
for (key, (image_root, json_file)) in splits_per_dataset.items():
register_lvis_instances(key, get_lvis_instances_meta(dataset_name), (os.path.join(root, json_file) if ('://' not in json_file)... |
class _FdHolder():
fd: int
def __init__(self, fd: int) -> None:
self.fd = (- 1)
if (not isinstance(fd, int)):
raise TypeError('file descriptor must be an int')
self.fd = fd
self._original_is_blocking = os.get_blocking(fd)
os.set_blocking(fd, False)
def clo... |
class cached_property(property):
def __get__(self, obj, objtype=None):
if (obj is None):
return self
if (self.fget is None):
raise AttributeError('unreadable attribute')
attr = ('__cached_' + self.fget.__name__)
cached = getattr(obj, attr, None)
if (ca... |
def get_named_bins_formatter(bins, names, show_values=False):
def formatter(x, pos):
if (len(names) != (len(bins) + 1)):
raise AssertionError(f'EOmaps: the provided number of names ({len(names)}) does not match! Expected {(len(bins) + 1)} names.')
b = np.digitize(x, bins, right=True)
... |
def prune_by_percentile(percent, resample=False, reinit=False, **kwargs):
global step
global mask
global model
step = 0
for (name, param) in model.named_parameters():
if ('weight' in name):
tensor = param.data.cpu().numpy()
alive = tensor[np.nonzero(tensor)]
... |
def test_keithley2000(monkeypatch):
monkeypatch.setattr(visa.GpibInstrument, 'interface_type', VI_INTF_GPIB)
monkeypatch.setattr(visa.GpibInstrument, 'stb', 64)
print('Test start')
keithley = visa.GpibInstrument(12)
milliseconds = 500
number_of_values = 10
keithley.write(('F0B2M2G0T2Q%dI%dX'... |
class TestPluginManager():
def test_default(self, isolation):
builder = MockBuilder(str(isolation))
assert isinstance(builder.plugin_manager, PluginManager)
def test_reuse(self, isolation):
plugin_manager = PluginManager()
builder = MockBuilder(str(isolation), plugin_manager=plug... |
_network('example')
class ExampleGNN(torch.nn.Module):
def __init__(self, dim_in, dim_out, num_layers=2, model_type='GCN'):
super().__init__()
conv_model = self.build_conv_model(model_type)
self.convs = nn.ModuleList()
self.convs.append(conv_model(dim_in, dim_in))
for _ in ra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.