code stringlengths 281 23.7M |
|---|
class Interpreter(_Decoratable, ABC, Generic[(_Leaf_T, _Return_T)]):
def visit(self, tree: Tree[_Leaf_T]) -> _Return_T:
return self._visit_tree(tree)
def _visit_tree(self, tree: Tree[_Leaf_T]):
f = getattr(self, tree.data)
wrapper = getattr(f, 'visit_wrapper', None)
if (wrapper i... |
class TimeTests(unittest.TestCase):
def test_humanize_delta_handle_unknown_units(self):
actual = time.humanize_delta(relativedelta(days=2, hours=2), precision='elephants', max_units=2)
self.assertEqual(actual, '2 days and 2 hours')
def test_humanize_delta_handle_high_units(self):
actual ... |
class Input(Queue, Readable, Writable):
def __init__(self, maxsize=BUFFER_SIZE):
Queue.__init__(self, maxsize)
self._runlevel = 0
self._writable_runlevel = 0
self.on_initialize = noop
self.on_begin = noop
self.on_end = noop
self.on_finalize = noop
def put(... |
class PNet(nn.Module):
def __init__(self, pnet_type='vgg', pnet_rand=False, use_gpu=True):
super(PNet, self).__init__()
self.use_gpu = use_gpu
self.pnet_type = pnet_type
self.pnet_rand = pnet_rand
self.shift = torch.Tensor([(- 0.03), (- 0.088), (- 0.188)]).view(1, 3, 1, 1)
... |
def eez(countries, geo_crs, country_shapes, EEZ_gpkg, out_logging=False, distance=0.01, minarea=0.01, tolerance=0.01):
if out_logging:
logger.info('Stage 2 of 5: Create offshore shapes')
df_eez = load_EEZ(countries, geo_crs, EEZ_gpkg)
eez_countries = [cc for cc in countries if df_eez.name.str.contai... |
def get_up_block(up_block_type, num_layers, in_channels, out_channels, prev_output_channel, temb_channels, add_upsample, resnet_eps, resnet_act_fn, attn_num_head_channels, resnet_groups=None, cross_attention_dim=None):
up_block_type = (up_block_type[7:] if up_block_type.startswith('UNetRes') else up_block_type)
... |
def save_checkpoint(model, filename, optimizer=None, meta=None):
if (meta is None):
meta = {}
elif (not isinstance(meta, dict)):
raise TypeError(f'meta must be a dict or None, but got {type(meta)}')
meta.update(mmcv_version=mmcv.__version__, time=time.asctime())
if is_module_wrapper(mode... |
class GroundtruthFilterWithNanBoxTest(tf.test.TestCase):
def test_filter_groundtruth_with_nan_box_coordinates(self):
input_tensors = {fields.InputDataFields.groundtruth_boxes: [[np.nan, np.nan, np.nan, np.nan], [0.2, 0.4, 0.1, 0.8]], fields.InputDataFields.groundtruth_classes: [1, 2], fields.InputDataFields... |
def test_select_column_using_window_function_with_parameters():
sql = 'INSERT INTO tab1\nSELECT col0,\n max(col3) over (partition BY col1 ORDER BY col2 DESC) AS rnum,\n col4\nFROM tab2'
assert_column_lineage_equal(sql, [(ColumnQualifierTuple('col0', 'tab2'), ColumnQualifierTuple('col0', 'tab1')), (C... |
def convert_examples_to_features(examples, tokenizer, query_templates, unseen_arguments, nth_query, is_training):
features = []
for (example_id, example) in enumerate(examples):
for event in example.events:
trigger_offset = (event[0][0] - example.s_start)
event_type = event[0][1]... |
class DescribeTabStops():
def it_knows_its_length(self, len_fixture):
(tab_stops, expected_value) = len_fixture
assert (len(tab_stops) == expected_value)
def it_can_iterate_over_its_tab_stops(self, iter_fixture):
(tab_stops, expected_count, tab_stop_, TabStop_, expected_calls) = iter_fix... |
def init_distributed_mode(args):
if args.dist_on_itp:
args.rank = int(os.environ['OMPI_COMM_WORLD_RANK'])
args.world_size = int(os.environ['OMPI_COMM_WORLD_SIZE'])
args.gpu = int(os.environ['OMPI_COMM_WORLD_LOCAL_RANK'])
args.dist_url = ('tcp://%s:%s' % (os.environ['MASTER_ADDR'], os... |
_specialize
_rewriter([Sum, Prod])
def local_sum_prod_of_mul_or_div(fgraph, node):
[node_inps] = node.inputs
if (not node_inps.owner):
return None
inner_op = node_inps.owner.op
if (not ((inner_op == mul) or (inner_op == true_div))):
return None
reduced_axes = node.op.axis
if (red... |
def classifier_fn_from_tfhub(output_fields, inception_model, return_tensor=False):
if isinstance(output_fields, six.string_types):
output_fields = [output_fields]
def _classifier_fn(images):
output = inception_model(images)
if (output_fields is not None):
output = {x: output[... |
class ChannelAttention(nn.Module):
def __init__(self):
super().__init__()
self.gap = nn.AdaptiveAvgPool2d(1)
self.attention = nn.Sequential(nn.Linear(512, 32), nn.BatchNorm1d(32), nn.ReLU(inplace=True), nn.Linear(32, 512), nn.Sigmoid())
def forward(self, sa):
sa = self.gap(sa)
... |
class FeatureConfig(object):
def __init__(self, name, dtype, size, default_value=None):
assert (dtype in ('int64', 'float32', 'string'))
self.name = name
self.dtype = {'int64': tf.int64, 'float32': tf.float32, 'string': tf.string}[dtype]
self.size = size
if (default_value is ... |
class DisconnectTLV(TLV):
typ = 1
def __init__(self):
super(DisconnectTLV, self).__init__()
def getPayload(self):
return b''
def parsePayload(cls, data):
if (len(data) > 0):
raise TypeError('DisconnectTLV must not contain data. got {0!r}'.format(data))
return ... |
class BaseTransformer(pl.LightningModule):
def __init__(self, hparams: argparse.Namespace, num_labels=None, mode='base', config=None, tokenizer=None, model=None, **config_kwargs):
super().__init__()
self.save_hyperparameters(hparams)
self.step_count = 0
self.output_dir = Path(self.hp... |
def load_collectors_from_paths(paths):
collectors = {}
if (paths is None):
return
if isinstance(paths, basestring):
paths = paths.split(',')
paths = map(str.strip, paths)
load_include_path(paths)
for path in paths:
if (not os.path.exists(path)):
raise OSEr... |
def test_async_subproc_command_eq():
c = Command('cmd')
assert (c == c)
assert (Command('cmd') == Command('cmd'))
assert (Command('cmd') != Command('other'))
assert (Command([1, 2, 3]) == Command([1, 2, 3]))
assert (Command([1, 2, 3]) != Command([11, 22, 33]))
assert (Command('arb') != 'arb'... |
def tensor2edge(tensor):
print(tensor.shape)
tensor = (torch.squeeze(tensor) if (len(tensor.shape) > 2) else tensor)
tmp = torch.sigmoid(tensor)
tmp = tmp.cpu().detach().numpy()
tmp = np.uint8(image_normalization(tmp))
tmp = cv.bitwise_not(tmp)
tmp = cv.cvtColor(tmp, cv.COLOR_GRAY2BGR)
c... |
def _results_to_dataframe(results: ExecutableGroupResult, func: Callable[([ExecutableResult, QuantumRuntimeConfiguration, SharedRuntimeInfo], Dict)]) -> pd.DataFrame:
return pd.DataFrame([func(result, results.runtime_configuration, results.shared_runtime_info) for result in results.executable_results]) |
class OAuth2PkceS256Test(OAuth2Test):
def do_login(self):
user = super().do_login()
requests = latest_requests()
auth_request = [r for r in requests if (self.backend.authorization_url() in r.url)][0]
code_challenge = auth_request.querystring.get('code_challenge')[0]
code_chal... |
def garbage_collect_storage(storage_id_whitelist):
if (len(storage_id_whitelist) == 0):
return []
def placements_to_filtered_paths_set(placements_list):
if (not placements_list):
return set()
with ensure_under_transaction():
content_checksums = set([placement.stor... |
def lr_setter(optimizer, epoch, args, bl=False):
lr = args.lr
if bl:
lr = (args.lrbl * (0.1 ** (epoch // (args.epochb * 0.5))))
elif args.cos:
lr *= ((0.01 + math.cos((0.5 * ((math.pi * epoch) / args.epochs)))) / 1.01)
else:
if (epoch >= args.epochs_decay[0]):
lr *= 0... |
def remove_s(data):
if verbose:
print(('#' * 10), 'Step - Remove "s:')
local_vocab = {}
temp_vocab = _check_vocab(data, local_vocab, response='unknown_list')
temp_vocab = [k for k in temp_vocab if _check_replace(k)]
temp_dict = {k: k[:(- 2)] for k in temp_vocab if (_check_replace(k) and (k.l... |
class VirtualenvRole(Role):
def __init__(self, prov, context):
super(VirtualenvRole, self).__init__(prov, context)
self.user = context['user']
self.base_directory = None
def get_base_directory(self):
return (self.base_directory or os.path.join(self.__get_user_dir(), '.virtualenvs... |
class TestDarnerCollector(CollectorTestCase):
def setUp(self):
config = get_collector_config('DarnerCollector', {'interval': 10, 'hosts': ['localhost:22133']})
self.collector = DarnerCollector(config, None)
def test_import(self):
self.assertTrue(DarnerCollector)
(Collector, 'publish'... |
def tent_generator(H, slope=1, bound=0.6):
data = Data()
(x, data.step_size) = np.linspace((- 1), 1, num=H, retstep=True)
y = np.linspace((- 1), 1, num=H)
(XX, YY) = np.meshgrid(x, y)
YY = np.flip(YY, axis=0)
z = np.zeros_like(XX)
zx = np.zeros_like(XX)
zy = np.zeros_like(XX)
mask_to... |
class SpatialWeighting(nn.Module):
def __init__(self, channels, ratio=16, conv_cfg=None, norm_cfg=None, act_cfg=(dict(type='ReLU'), dict(type='Sigmoid'))):
super().__init__()
if isinstance(act_cfg, dict):
act_cfg = (act_cfg, act_cfg)
assert (len(act_cfg) == 2)
assert mmcv... |
def get_restart_epoch() -> Union[(int, str)]:
if (constants.restart or (constants.job_type == 'test')):
generation_path = (constants.job_dir + 'generation.log')
epoch = 'NA'
row = (- 1)
while (not isinstance(epoch, int)):
epoch_key = read_row(path=generation_path, row=row... |
def main():
logs_dir = 'logs'
headers = ['name', 'model', 'git_hash', 'pretrained_model', 'epoch', 'iteration', 'valid/mean_iu']
rows = []
for log in os.listdir(logs_dir):
log_dir = osp.join(logs_dir, log)
if (not osp.isdir(log_dir)):
continue
try:
log_fil... |
_api()
class partition_unique(Stream):
_graphviz_shape = 'diamond'
def __init__(self, upstream, n: int, key: Union[(Hashable, Callable[([Any], Hashable)])]=identity, keep: str='first', **kwargs):
self.n = n
self.key = key
self.keep = keep
self._buffer = {}
self._metadata_... |
def pip_install(package, remove=False):
if (not report_view_param()):
report_view_param(True)
QTimer.singleShot(2000, (lambda : report_view_param(False)))
postfix = ('.exe' if (platform.system() == 'Windows') else '')
bin_path = os.path.dirname(sys.executable)
exe_path = os.path.join(bin... |
class CASClientV1(CASClientBase):
logout_redirect_param_name = 'url'
def verify_ticket(self, ticket):
params = [('ticket', ticket), ('service', self.service_url)]
url = ((urllib_parse.urljoin(self.server_url, 'validate') + '?') + urllib_parse.urlencode(params))
page = self.session.get(ur... |
class TestBaseEncode(ElectrumTestCase):
def test_base43(self):
tx_hex = 'cd0e96f9ca202e017ca3465e3c13373c0df3a4cdd91c1fd02ea42a1a65d2afdffffff757da7cf8322e5063785e2d8ada74702d2648fa2add2d533ba83c52eb110dffdffffff02d07eb544c86eaf95e3bb3b6d2cabb12ab40fc59cad9cace0d066fbfcf150a5a1bbc4f312cd2eb080e8d8a47e5f2ce1... |
class StubSource():
def __init__(self, module: str, path: (str | None)=None, runtime_all: (list[str] | None)=None) -> None:
self.source = BuildSource(path, module, None)
self.runtime_all = runtime_all
self.ast: (MypyFile | None) = None
def __repr__(self) -> str:
return f'StubSour... |
def test_find_MAP_discrete():
tol1 = (2.0 ** (- 11))
tol2 = (2.0 ** (- 6))
alpha = 4
beta = 4
n = 20
yes = 15
with pm.Model() as model:
p = pm.Beta('p', alpha, beta)
pm.Binomial('ss', n=n, p=p)
pm.Binomial('s', n=n, p=p, observed=yes)
map_est1 = find_MAP()
... |
def attention_mask(loss_mask, prefix_lm=True):
device = loss_mask.device
(batch_size, q_len) = loss_mask.size()
axis = torch.arange(q_len).to(device)
start = axis.unsqueeze(0).masked_fill((~ loss_mask), .0).min(dim=1).values
end = axis.unsqueeze(0).masked_fill((~ loss_mask), (- .0)).max(dim=1).value... |
def main():
pybullet_planning.connect()
pybullet_planning.add_data_path()
p.loadURDF('plane.urdf')
p.resetDebugVisualizerCamera(cameraDistance=1, cameraYaw=(- 60), cameraPitch=(- 20), cameraTargetPosition=(0, 0, 0.4))
reorientbot.pybullet.create_bin(X=0.4, Y=0.6, Z=0.2)
reorientbot.pybullet.step... |
def load_multiple_centralized_dataset(load_as, args, process_id, mode, task, dataset_list, datadir_list, batch_size, num_workers, data_sampler=None, resize=32, augmentation='default'):
train_dl_dict = {}
test_dl_dict = {}
train_ds_dict = {}
test_ds_dict = {}
class_num_dict = {}
train_data_num_di... |
def unpack_values(value: Value, ctx: CanAssignContext, target_length: int, post_starred_length: Optional[int]=None) -> Union[(Sequence[Value], CanAssignError)]:
if isinstance(value, MultiValuedValue):
subvals = [unpack_values(val, ctx, target_length, post_starred_length) for val in value.vals]
good_... |
def setUpModule():
global mol, m, h1e, g2e, ci0, cis
global norb, nelec, orbsym
mol = gto.Mole()
mol.verbose = 0
mol.atom = '\n O 0. 0. 0.\n H 0. -0.757 0.587\n H 0. 0.757 0.587'
mol.basis = 'sto-3g'
mol.symmetry = 1
mol.build()
m = scf.RHF(mo... |
def test_label_compression_attack():
packet = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x03atk\x00\x00\x01\x80\x01\x00\x00\x00\x01\x00\x04\xc0\xa8\xd0\x05\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03atk\x03at... |
class TestPXRD(unittest.TestCase):
def test_similarity(self):
sites = ['8a']
C1 = pyxtal()
C1.from_random(3, 227, ['C'], [8], sites=[['8a']])
xrd1 = C1.get_XRD()
C2 = C1.subgroup_once(eps=0.001)
xrd2 = C1.get_XRD()
p1 = xrd1.get_profile()
p2 = xrd2.get... |
def sample(seq_str, experiment_directory='seq2seq/experiment', checkpoint='2019_05_18_20_32_54', resume=True, log_level='info'):
logging.basicConfig(format=LOG_FORMAT, level=getattr(logging, log_level.upper()))
logging.info('experiment_directory: %s', experiment_directory)
logging.info('checkpoint: %s', che... |
class BackUp(models.Model):
author = models.ForeignKey('Author', on_delete=models.CASCADE)
file = models.FileField(upload_to=user_directory_backup)
is_ready = models.BooleanField(default=False)
date_created = models.DateTimeField(auto_now_add=True)
def process(self):
if self.is_ready:
... |
def validate_data(gtFilePath, submFilePath, evaluationParams):
gt = rrc_evaluation_funcs.load_zip_file(gtFilePath, evaluationParams['GT_SAMPLE_NAME_2_ID'])
subm = rrc_evaluation_funcs.load_zip_file(submFilePath, evaluationParams['DET_SAMPLE_NAME_2_ID'], True)
for k in gt:
rrc_evaluation_funcs.valida... |
_config
def test_chord_stack(manager):
manager.test_window('two')
manager.test_window('one')
assert (manager.c.get_groups()['a']['focus'] == 'one')
manager.c.simulate_keypress(['control'], 'd')
manager.c.simulate_keypress([], 'z')
assert (manager.c.get_groups()['a']['focus'] == 'two')
manage... |
def prepare_ocp(biorbd_model_path: str, final_time: float, n_shooting: int, ode_solver: OdeSolverBase=OdeSolver.RK4(), phase_dynamics: PhaseDynamics=PhaseDynamics.SHARED_DURING_THE_PHASE, expand_dynamics: bool=True) -> OptimalControlProgram:
bio_model = BiorbdModel(biorbd_model_path)
objective_functions = Objec... |
class AsyncState(State):
async def enter(self, event_data):
_LOGGER.debug('%sEntering state %s. Processing callbacks...', event_data.machine.name, self.name)
(await event_data.machine.callbacks(self.on_enter, event_data))
_LOGGER.info('%sFinished processing state %s enter callbacks.', event_... |
.parametrize('with_suffix,', [(False,), (True,)])
def test_inject_include_apps(pipx_temp_env, capsys, with_suffix):
install_args = []
suffix = ''
if with_suffix:
suffix = '_x'
install_args = [f'--suffix={suffix}']
assert (not run_pipx_cli(['install', 'pycowsay', *install_args]))
asse... |
def build_test_loader(cfg, is_train=False):
path_catalog = import_file('smoke.config.paths_catalog', cfg.PATHS_CATALOG, True)
DatasetCatalog = path_catalog.DatasetCatalog
transforms = build_transforms(cfg, is_train)
datasets = build_dataset(cfg, transforms, DatasetCatalog, is_train)
data_loaders = [... |
class _AssertRaisesContext(object):
def __init__(self, expected, test_case):
self.expected = expected
self.failureException = test_case.failureException
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, tb):
if (exc_type is None):
exc_name =... |
class Test_util(unittest.TestCase):
def test_to_bytes(self):
self.assertEqual(serial.to_bytes([1, 2, 3]), b'\x01\x02\x03')
self.assertEqual(serial.to_bytes(b'\x01\x02\x03'), b'\x01\x02\x03')
self.assertEqual(serial.to_bytes(bytearray([1, 2, 3])), b'\x01\x02\x03')
self.assertRaises(Ty... |
def download(message: Soup.Message, cancellable: Gio.Cancellable, callback: Callable, data: Any, try_decode: bool=False, failure_callback: (FailureCallback | None)=None):
def received(request, ostream):
ostream.close(None)
bs = ostream.steal_as_bytes().get_data()
if (not try_decode):
... |
class Effect1261(BaseEffect):
runTime = 'early'
type = 'passive'
def handler(fit, implant, context, projectionRange, **kwargs):
fit.appliedImplants.filteredItemMultiply((lambda mod: (mod.item.group.name == 'Cyberimplant')), 'velocityBonus', implant.getModifiedItemAttr('implantSetSerpentis'), **kwarg... |
def _ensure_datetime_tzinfo(dt: datetime.datetime, tzinfo: (datetime.tzinfo | None)=None) -> datetime.datetime:
if (dt.tzinfo is None):
dt = dt.replace(tzinfo=UTC)
if (tzinfo is not None):
dt = dt.astimezone(get_timezone(tzinfo))
if hasattr(tzinfo, 'normalize'):
dt = tzinfo.n... |
class AdditionalSkipNamesModuleTest(fake_filesystem_unittest.TestCase):
def setUp(self):
self.setUpPyfakefs(additional_skip_names=[pyfakefs.tests.import_as_example])
def test_path_exists(self):
self.assertTrue(pyfakefs.tests.import_as_example.exists_this_file())
def test_fake_path_does_not_e... |
.parametrize('bucket, username, password', [pytest.param(_TEST_BUCKET, _TEST_USER, _TEST_PASSWORD, id='same credentials'), pytest.param('another_bucket', 'blech', 'password', id='different credentials')])
def test_copy(bucket, username, password, storage_engine):
another_engine = S3Storage(_TEST_CONTEXT, 'another/p... |
class PreOCIModel(KeyServerDataInterface):
def list_service_keys(self, service):
return data.model.service_keys.list_service_keys(service)
def get_service_key(self, signer_kid, service=None, alive_only=True, approved_only=True):
try:
key = data.model.service_keys.get_service_key(sign... |
def test_several_recursive_types():
dumped_data = {'left': {'left': {'left': None, 'right': None}, 'right': {'left': None, 'right': None}}, 'right': {'left': None, 'right': None}}
loaded_data = Tree(left=Tree(left=Tree(), right=Tree()), right=Tree())
assert (retort.dump(loaded_data) == dumped_data)
asse... |
def parse_selection(selection, *, op=None):
parsed = _benchmark.parse_benchmark(selection, fail=False)
(spec, metafile) = (parsed if parsed else (None, None))
if (parsed and spec.version):
kind = 'benchmark'
(spec, metafile) = parsed
if metafile:
parsed = _benchmark.Bench... |
def test_format_datetime(timezone_getter):
dt = datetime(2007, 4, 1, 15, 30)
assert (dates.format_datetime(dt, locale='en_US') == 'Apr 1, 2007, 3:30:00\u202fPM')
full = dates.format_datetime(dt, 'full', tzinfo=timezone_getter('Europe/Paris'), locale='fr_FR')
assert (full == 'dimanche 1 avril 2007, 17:30... |
class Tpl(BaseDB, AlchemyMixin):
__tablename__ = 'tpl'
id = Column(Integer, primary_key=True)
disabled = Column(TINYINT(1), nullable=False, server_default=text("'0'"))
public = Column(TINYINT(1), nullable=False, server_default=text("'0'"))
lock = Column(TINYINT(1), nullable=False, server_default=tex... |
class FilterEditView(EditBaseView):
class _REMOVE():
def __init__(self, filter_list: FilterList, list_type: ListType, filter_type: type[Filter], content: (str | None), description: (str | None), settings_overrides: dict, filter_settings_overrides: dict, loaded_settings: dict, loaded_filter_settings: dict, autho... |
(scope='module')
def inline_query_result_mpeg4_gif():
return InlineQueryResultMpeg4Gif(TestInlineQueryResultMpeg4GifBase.id_, TestInlineQueryResultMpeg4GifBase.mpeg4_url, TestInlineQueryResultMpeg4GifBase.thumbnail_url, mpeg4_width=TestInlineQueryResultMpeg4GifBase.mpeg4_width, mpeg4_height=TestInlineQueryResultMpe... |
class TestCase(unittest.TestCase, TestCaseMixin):
def __init__(self, methodName: str='runTest', additional_skip_names: Optional[List[Union[(str, ModuleType)]]]=None, modules_to_reload: Optional[List[ModuleType]]=None, modules_to_patch: Optional[Dict[(str, ModuleType)]]=None):
super().__init__(methodName)
... |
def do_EQUSIZED(op, stack, state):
length = getlen(op, state)
prev_size = state.esil['size']
state.esil['size'] = length
reg = stack.pop()
(val,) = pop_values(stack, state)
tmp = get_value(reg, state)
if (state.condition != None):
val = z3.If(state.condition, val, tmp)
state.regi... |
(params=[('chunk', 0), ('chunk', 1), ('enumerate', None)])
def sharding_spec(shape: Tuple[(int, int)], request: SubRequest) -> ShardingSpec:
(sharding_type, dim) = request.param
if (sharding_type == 'chunk'):
return ChunkShardingSpec(dim=dim, placements=[f'rank:{rank}/cpu' for rank in range(WORLD_SIZE)]... |
(short_help='Clip a raster to given bounds.')
('files', nargs=(- 1), type=click.Path(), required=True, metavar='INPUT OUTPUT')
_opt
_opt
_window_options
('--like', type=click.Path(exists=True), help='Raster dataset to use as a template for bounds')
_opt
_opt
_geographic_opt
_projected_opt
_opt
_options
('--with-complem... |
.parametrize('name', ['pypi', 'PyPI'])
def test_source_remove_pypi_and_other(name: str, tester_pypi_and_other: CommandTester, poetry_with_pypi_and_other: Poetry, source_existing: Source) -> None:
tester_pypi_and_other.execute(name)
assert (tester_pypi_and_other.io.fetch_output().strip() == 'Removing source with... |
def print_model_with_flops(model, total_flops, total_params, units='GFLOPs', precision=3, ost=sys.stdout, flush=False):
def accumulate_params(self):
if is_supported_instance(self):
return self.__params__
else:
sum = 0
for m in self.children():
sum ... |
def test_uninject_with_include_apps(pipx_temp_env, capsys, caplog):
assert (not run_pipx_cli(['install', 'pycowsay']))
assert (not run_pipx_cli(['inject', 'pycowsay', PKG['black']['spec'], '--include-deps', '--include-apps']))
assert (not run_pipx_cli(['uninject', 'pycowsay', 'black', '--verbose']))
ass... |
_args('v', 'i', 'none')
def softmax(g, input, dim, dtype=None):
input_dim = input.type().dim()
if input_dim:
if (dim < 0):
dim = (input_dim + dim)
if (input_dim == (dim + 1)):
softmax = g.op('Softmax', input, axis_i=dim)
if (dtype and (dtype.node().kind() != '... |
class IncrPyVars(Component):
def construct(s):
s.incr_in = b8(10)
s.incr_out = b8(0)
s.buf1 = b8(0)
s.buf2 = b8(0)
def upA():
s.buf1 = s.incr_in
s.incr_in += b8(10)
def upB():
s.buf2 = (s.buf1 + b8(1))
def upC():
... |
class NameTransformer(ast.NodeTransformer):
def __init__(self, class_replace_map: Optional[Dict[(str, str)]]=None, import_replace_map: Optional[Dict[(str, str)]]=None, rename_methods: Optional[Dict[(str, str)]]=None):
self.class_replace_map = (class_replace_map if (class_replace_map is not None) else {})
... |
def test_help_text(monkeypatch, capsys):
mock_exit = mock.Mock(side_effect=ValueError('raised in test to exit early'))
with mock.patch.object(sys, 'exit', mock_exit), pytest.raises(ValueError, match='raised in test to exit early'):
run_pipx_cli(['install', '--help'])
captured = capsys.readouterr()
... |
def test_ki_disabled_in_del() -> None:
def nestedfunction() -> bool:
return _core.currently_ki_protected()
def __del__() -> None:
assert _core.currently_ki_protected()
assert nestedfunction()
_core.disable_ki_protection
def outerfunction() -> None:
assert (not _core.curre... |
class Padding(Dict):
_show_valtype = False
def __init__(self, *, none_ok: bool=False, completions: _Completions=None) -> None:
super().__init__(keytype=String(), valtype=Int(minval=0, none_ok=none_ok), fixed_keys=['top', 'bottom', 'left', 'right'], none_ok=none_ok, completions=completions)
def to_py... |
def eval_dialogue_system(infile):
lines = open(infile, 'r').readlines()[1:]
f1_scores = []
rl_scores = []
answer_lengths = []
for line in lines:
line = json.loads(line)
answer = line['answer']
output = line['output'][0]
f1_scores.append(f1(output, answer))
rl_... |
def get_args_parser():
parser = argparse.ArgumentParser('ReferFormer training and inference scripts.', add_help=False)
parser.add_argument('--lr', default=0.0001, type=float)
parser.add_argument('--lr_backbone', default=5e-05, type=float)
parser.add_argument('--lr_backbone_names', default=['backbone.0']... |
def convert_sentence_to_features(sentence, max_seq_length, tokenizer):
sentence = tokenizer.tokenize(sentence)
sentence = sentence[0:(max_seq_length - 2)]
tokens = []
segment_ids = []
tokens.append('[CLS]')
segment_ids.append(0)
idx_tracker = 0
sentence_start_idx = 1
for token in sen... |
_REGISTRY.register(name='Trans2Seg')
class Trans2Seg(SegBaseModel):
def __init__(self):
super().__init__()
if self.backbone.startswith('mobilenet'):
c1_channels = 24
c4_channels = 320
else:
c1_channels = 256
c4_channels = 2048
vit_param... |
def train(config, workdir):
sample_dir = os.path.join(workdir, 'samples')
tf.io.gfile.makedirs(sample_dir)
tb_dir = os.path.join(workdir, 'tensorboard')
tf.io.gfile.makedirs(tb_dir)
writer = tensorboard.SummaryWriter(tb_dir)
score_model = mutils.create_model(config)
ema = ExponentialMovingAv... |
.unit()
.parametrize(('plugins', 'expected'), [([(None, DummyDist('pytask-plugin', '0.0.1'))], ['plugin-0.0.1']), ([(None, DummyDist('plugin', '1.0.0'))], ['plugin-1.0.0'])])
def test_format_plugin_names_and_versions(plugins, expected):
assert (_format_plugin_names_and_versions(plugins) == expected) |
def _bounds(scdf, **kwargs):
if scdf.empty:
return None
col_order = [c for c in scdf.columns]
by = kwargs.get('group_by')
if (not (type(by) is list)):
by = [by]
agg_dict = (kwargs.get('agg') if kwargs.get('agg') else {})
agg_dict.update({'Start': 'min', 'End': 'max', 'Chromosome'... |
def SparseCompRow_matmult(M, y, val, row, col, x, num_iterations):
range_it = range(num_iterations)
t0 = pyperf.perf_counter()
for _ in range_it:
for r in range(M):
sa = 0.0
for i in range(row[r], row[(r + 1)]):
sa += (x[col[i]] * val[i])
y[r] = sa... |
.parametrize('qtwe_version, setting, value, expected', [('6.6.1', 'policy.images', 'always', [('ImagePolicy', '0')]), ('6.6.1', 'policy.images', 'never', [('ImagePolicy', '1')]), ('6.6.1', 'policy.images', 'smart', [('ImagePolicy', '2'), ('ImageClassifierPolicy', '0')]), ('6.6.1', 'policy.images', 'smart-simple', [('Im... |
def create_rectangular_field_function(centre, side_lengths, penumbra_width, rotation=0):
width_profile = create_profile_function(0, side_lengths[0], penumbra_width)
length_profile = create_profile_function(0, side_lengths[1], penumbra_width)
theta = (((- rotation) / 180) * np.pi)
def field(x, y):
... |
class FlatSimilarityWrapper(nn.Module):
def __init__(self, x1_dim, x2_dim, prefix='attention', opt={}, dropout=None):
super(FlatSimilarityWrapper, self).__init__()
self.score_func_str = opt.get('{}_att_type'.format(prefix), 'none').lower()
self.att_dropout = DropoutWrapper(opt.get('{}_att_dr... |
.parametrize('shape', [[1.0], [1j], [1.0, 1.0], [1.0, 0.5], [1.0, (0.5 + 0.5j)], [(0.5 - 0.5j), (0.5 + 0.5j)], [1, 2, 3, 4, 5, 6, 7, 8], [1, 1, 1, 1, 1, 1, 1, 1]])
def test_create_one_particle_circuit(shape):
amplitudes = (shape / np.linalg.norm(shape))
qubits = cirq.LineQubit.range(len(amplitudes))
circuit... |
def parse_json(json_string, video_id, transform_source=None, fatal=True):
if transform_source:
json_string = transform_source(json_string)
try:
return json.loads(json_string)
except ValueError as ve:
errmsg = ('[-] %s: Failed to parse JSON ' % video_id)
if fatal:
... |
_to_string
class BuildError(RoutingException, LookupError):
def __init__(self, endpoint, values, method, adapter=None):
LookupError.__init__(self, endpoint, values, method)
self.endpoint = endpoint
self.values = values
self.method = method
self.adapter = adapter
_property... |
class TASFObjects(TestCase):
filename = os.path.join(DATA_DIR, 'silence-1.wma')
def test_invalid_header(self):
with warnings.catch_warnings():
warnings.simplefilter('ignore')
asf = ASF()
fileobj = BytesIO(b'0&\xb2u\x8ef\xcf\x11\xa6\xd9\x00\xaa\x00b\xcel\x19\xbf\x01\x00\x0... |
def merger_phase_calculation(min_switch_ind, final_i_index, i_phase, m_omega):
assert (type(min_switch_ind) == int), 'min_switch_ind should be an int.'
assert (type(final_i_index) == int), 'final_i_index should be an int.'
assert (type(i_phase) == list), 'i_phase should be a list.'
assert (type(m_omega)... |
(os.environ, {}, clear=True)
('pyinaturalist.auth.get_keyring_credentials')
('pyinaturalist.auth._get_jwt', return_value=NOT_CACHED_RESPONSE)
def test_get_access_token__missing_creds(mock_get_jwt, mock_keyring_credentials):
with pytest.raises(AuthenticationError):
get_access_token('username') |
class Solution():
def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:
if (bound < 2):
return []
(x_, y_) = ([1], [1])
if (x != 1):
i = 1
while (x_[(- 1)] <= bound):
x_.append((x ** i))
i += 1
if (y !... |
(sampled_from(([(tuple, Tuple), (tuple, tuple), (list, list), (list, List), (deque, deque), (deque, Deque), (set, Set), (set, set), (frozenset, frozenset), (frozenset, FrozenSet)] if is_py39_plus else [(tuple, Tuple), (list, List), (deque, Deque), (set, Set), (frozenset, FrozenSet)])))
def test_seq_of_bare_classes_stru... |
.parametrize('args, pkgs', [({'where': ['.'], 'namespaces': False}, {'pkg', 'other'}), ({'where': ['.', 'dir1'], 'namespaces': False}, {'pkg', 'other', 'dir2'}), ({'namespaces': True}, {'pkg', 'other', 'dir1', 'dir1.dir2'}), ({}, {'pkg', 'other', 'dir1', 'dir1.dir2'})])
def test_find_packages(tmp_path, args, pkgs):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.