code stringlengths 281 23.7M |
|---|
class VanMlpLayer(nn.Sequential):
def __init__(self, in_channels: int, hidden_size: int, out_channels: int, hidden_act: str='gelu', dropout_rate: float=0.5):
super().__init__()
self.in_dense = nn.Conv2d(in_channels, hidden_size, kernel_size=1)
self.depth_wise = nn.Conv2d(hidden_size, hidden_... |
class ClassyModelWrapper():
def __init__(self, classy_model):
self.classy_model = classy_model
def __getattr__(self, name):
if ((name != 'classy_model') and hasattr(self, 'classy_model')):
attr = getattr(self.classy_model, name)
if isinstance(attr, types.MethodType):
... |
def get_imagenet(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), root='./data', base_folder='imagenet'):
transform_train = transforms.Compose([transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mean, std)])
transform_test = transforms.Compose... |
def cec_dc_snl_ac_arrays(cec_module_cs5p_220m, cec_inverter_parameters, sapm_temperature_cs5p_220m):
module_parameters = cec_module_cs5p_220m.copy()
module_parameters['b'] = 0.05
module_parameters['EgRef'] = 1.121
module_parameters['dEgdT'] = (- 0.0002677)
temp_model_params = sapm_temperature_cs5p_2... |
class FSDPOptimizerAdapter():
def __init__(self, module: FSDP, optimizer: torch.optim.Optimizer) -> None:
self.module = module
self.optimizer = optimizer
def state_dict(self) -> Dict[(str, Any)]:
optim_state_dict = FSDP.optim_state_dict(self.module, self.optimizer)
return optim_s... |
class Effect5381(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Medium Energy Turret')), 'trackingSpeed', ship.getModifiedItemAttr('shipBonusABC1'), skill='Amarr Battlecruiser', **kwargs) |
def main():
parser = ArgumentParser(description=CMDLINE_HELP)
parser.add_argument('--noserver', action='store_true', dest='noserver', default=False, help='Do not start Server process')
parser.add_argument('--noportal', action='store_true', dest='noportal', default=False, help='Do not start Portal process')
... |
class PBSProJob(cpi.Job):
def __init__(self, api, adaptor):
_cpi_base = super(PBSProJob, self)
_cpi_base.__init__(api, adaptor)
def _get_impl(self):
return self
_CALL
def init_instance(self, job_info):
self.jd = job_info['job_description']
self.js = job_info['job_... |
def test_special_characters():
s = '\n[\n]\n^\n\\\n(\n)\n(?:\n-\n|\n\\w\n'
assert (list(MyLexer().get_tokens(s)) == [(Token.Name, '['), (Token.Text, '\n'), (Token.Name, ']'), (Token.Text, '\n'), (Token.Name, '^'), (Token.Text, '\n'), (Token.Name, '\\'), (Token.Text, '\n'), (Token.Name, '('), (Token.Text, '\n'),... |
class MigratableDb():
def __init__(self, ddbb):
self.ddbb = ddbb
def is_empty(self):
metadata = MetaData()
metadata.bind = self.ddbb.engine
metadata.reflect()
tables = metadata.tables
return (not tables)
def is_versioned(self):
try:
self.ge... |
class AutoSamSeg(nn.Module):
def __init__(self, image_encoder, seg_decoder, img_size=1024):
super().__init__()
self.img_size = img_size
self.image_encoder = image_encoder
self.mask_decoder = seg_decoder
self.pe_layer = PositionEmbeddingRandom(128)
def forward(self, x):
... |
class TestRiskDifference():
def test_risk_difference_equal_to_0(self, counts_1):
rd = risk_difference(counts_1[0], counts_1[1], counts_1[2], counts_1[3])
assert (rd.point_estimate == 0)
def test_risk_difference_equal_to_half(self):
rd = risk_difference(50, 50, 25, 75)
npt.assert_... |
class Kernel(abc.ABC):
def __call__(self, x: torch.Tensor, y: Union[(None, torch.Tensor)]=None) -> torch.Tensor:
if (y is None):
y = x
return self._call_impl(x, y)
def _call_impl(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
def string_id(self):
def effective_dim(s... |
class BaseOCR(BasePlugin):
__name__ = 'BaseOCR'
__type__ = 'base'
__version__ = '0.28'
__status__ = 'stable'
__description__ = 'OCR base plugin'
__license__ = 'GPLv3'
__authors__ = [('pyLoad team', '')]
def __init__(self, pyfile):
self._init(pyfile.m.pyload)
self.pyfile =... |
class UnitsSystem(SourceManagedClass):
def __init__(self, sources: Optional[Callable]=None):
super().__init__({k: sources(k) for k in sources()})
self.separate_value_and_unit_RE = re.compile(u'([-+]?[0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)?)(?:[ \t]*(.*))?')
self.split_units_RE = re.compile(u'(?:... |
def _setup_server(webio_handler, port=0, host='', static_dir=None, max_buffer_size=((2 ** 20) * 200), **tornado_app_settings):
if (port == 0):
port = get_free_port()
handlers = [('/', webio_handler)]
if (static_dir is not None):
handlers.append(('/static/(.*)', tornado.web.StaticFileHandler,... |
class MultiOutputModel(torch.nn.Module):
def __init__(self):
super(MultiOutputModel, self).__init__()
self.layer = TupleOutputModel()
self.conv1 = torch.nn.Conv2d(2, 4, kernel_size=3, padding=1)
self.conv2 = torch.nn.Conv2d(4, 4, kernel_size=3, padding=1)
self.conv3 = torch.n... |
_function
def create_pak_backups(game_root: Path, backup_files_path: Path, progress_update: ProgressUpdateCallable):
pak_folder = backup_files_path.joinpath('paks')
pak_folder.mkdir(parents=True, exist_ok=True)
files_folder = game_root.joinpath('files')
for (i, pak) in enumerate(_ECHOES_PAKS):
p... |
def get_feature_dimensions(parameters: dict) -> Tuple[(int, int, int, int)]:
n_atom_types = len(parameters['atom_types'])
n_formal_charge = len(parameters['formal_charge'])
n_numh = (int(((not parameters['use_explicit_H']) and (not parameters['ignore_H']))) * len(parameters['imp_H']))
n_chirality = (int... |
class GlibTranslations(gettext.GNUTranslations):
def __init__(self, fp=None):
self.path = ((fp and fp.name) or '')
self._catalog = {}
self.plural = (lambda n: (n != 1))
gettext.GNUTranslations.__init__(self, fp)
self._debug_text = None
def ugettext(self, message):
... |
def val(model, dataloader, metrics_manager):
model.eval()
if opt.multiclass:
criterion = CrossEntropyLoss()
else:
criterion = BCEWithLogitsLoss()
metrics_manager.reset()
for (_, data) in enumerate(dataloader):
(inputs, labels) = data
(loss, y_pred, y_true) = forward_s... |
def myUpSample2X(layer_input, skip_input, filters, f_size=3, dropout_rate=0):
u = UpSampling2D(size=2)(layer_input)
u = Conv2D(filters, kernel_size=f_size, strides=1, padding='same', activation='relu')(u)
if dropout_rate:
u = Dropout(dropout_rate)(u)
u = BatchNormalization(momentum=0.8)(u)
u... |
class keep_wl():
def __init__(self, labels):
self.loss = torch.zeros(labels.shape[0], dtype=torch.float).cuda(non_blocking=True)
self.weight = torch.zeros(labels.shape[0], dtype=torch.float).cuda(non_blocking=True)
def __call__(self, epoch_loss, epoch_weight, index):
self.loss[index] = e... |
class CheckNanLossHook(ClassyHook):
on_start = ClassyHook._noop
on_phase_start = ClassyHook._noop
on_forward = ClassyHook._noop
on_backward = ClassyHook._noop
on_phase_end = ClassyHook._noop
on_end = ClassyHook._noop
on_step = ClassyHook._noop
on_update = ClassyHook._noop
def on_loss... |
class TestFileFileYAMLReaderMultipleFileTypes(unittest.TestCase):
def setUp(self):
patterns1 = ['a.nc']
patterns2 = ['b.nc']
patterns3 = ['geo.nc']
res_dict = {'reader': {'name': 'fake', 'sensors': ['canon']}, 'file_types': {'ftype1': {'name': 'ft1', 'file_patterns': patterns1}, 'fty... |
def interrogate_collection_type(t):
expr = _norm_input(t)
style = None
members = None
view = None
base = None
if (expr.name in _VARIADIC):
(view, base) = _VARIADIC[expr.name]
(field,) = expr.fields
if isinstance(field, UnionExp):
style = 'composite'
... |
_tokenizers
class MgpstrTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = MgpstrTokenizer
test_rust_tokenizer = False
from_pretrained_kwargs = {}
test_seq2seq = False
def setUp(self):
super().setUp()
vocab = ['[GO]', '[s]', '0', '1', '2', '3', '4', '5', '6'... |
class FAP2(Stage):
_format = [E(1, 4, x_fixed(b'FAP2'), dummy=True), E(6, 7, 'i2'), E(9, 9, 'a1'), E(11, 14, 'i4'), E(16, 23, 'f8.3'), E(25, 27, 'i3'), E(29, 53, 'a25')]
output_units = Units.T(help='output units code (V=volts, A=amps, C=counts)')
decimation = Int.T(optional=True, help='decimation')
corr... |
class BackendMock(_BackendBase):
_version = None
def bugzilla_version(self):
return {'version': self._version}
def __helper(self, args):
prevfuncname = inspect.stack()[1][3]
func_args = getattr(self, ('_%s_args' % prevfuncname))
func_return = getattr(self, ('_%s_return' % pre... |
def test_two_debits(sdd):
payment1 = {'name': 'Test & Co.', 'IBAN': 'NL50BANK', 'BIC': 'BANKNL2A', 'amount': 1012, 'type': 'FRST', 'collection_date': datetime.date.today(), 'mandate_id': '1234', 'mandate_date': datetime.date.today(), 'description': 'Test transaction1', 'endtoend_id': 'ebd75e7e649375d91b33dc11ae44c0... |
def test_filerewriter_files_in_to_out_no_out(temp_file_creator):
rewriter = ArbRewriter('formatter')
file1 = temp_file_creator()
with patch_logger('pypyr.utils.filesystem', logging.INFO) as mock_logger_info:
rewriter.files_in_to_out(file1)
assert (mock_logger_info.mock_calls == [call(f'edited & ... |
class FixFuncattrs(fixer_base.BaseFix):
BM_compatible = True
PATTERN = "\n power< any+ trailer< '.' attr=('func_closure' | 'func_doc' | 'func_globals'\n | 'func_name' | 'func_defaults' | 'func_code'\n | 'func_dict') > any* >\n "
def tra... |
class ConditionalDetrOnnxConfig(OnnxConfig):
torch_onnx_minimum_version = version.parse('1.11')
def inputs(self) -> Mapping[(str, Mapping[(int, str)])]:
return OrderedDict([('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'})])
def atol_for_validat... |
class NotInSetConstraint(Constraint):
def __init__(self, set):
self._set = set
def __call__(self, variables, domains, assignments, forwardcheck=False):
raise RuntimeError("Can't happen")
def preProcess(self, variables: Sequence, domains: dict, constraints: List[tuple], vconstraints: dict):
... |
class Tlibrary_utils(TestCase):
def test_basic(self):
if is_windows():
res = split_scan_dirs(':Z:\\foo:C:/windows:')
self.assertEqual(res, ['Z:\\foo', 'C:/windows'])
else:
res = split_scan_dirs(f':{STANDARD_PATH}:{OTHER_PATH}:')
self.assertEqual(res, [... |
def find_vcs_root(path, markers=('.git',)):
if osp.isfile(path):
path = osp.dirname(path)
(prev, cur) = (None, osp.abspath(osp.expanduser(path)))
while (cur != prev):
if any((osp.exists(osp.join(cur, marker)) for marker in markers)):
return cur
(prev, cur) = (cur, osp.spl... |
def get_cosine_schedule_with_warmup(optimizer, num_training_steps, num_warmup_steps=0, num_cycles=(7.0 / 16.0), last_epoch=(- 1)):
def _lr_lambda(current_step):
if (current_step < num_warmup_steps):
return (float(current_step) / float(max(1, num_warmup_steps)))
no_progress = (float((curr... |
_module()
def constant_init(module, val, bias=0):
if (hasattr(module, 'weight') and (module.weight is not None)):
nn.init.constant_(module.weight, val)
elif hasattr(module, 'kernel'):
nn.init.constant_(module.kernel, val)
if (hasattr(module, 'bias') and (module.bias is not None)):
nn... |
class _CookieDBManager():
_db = None
_cache_dir = _os.path.join(_ad.user_cache_dir(), 'py-yfinance')
def get_database(cls):
if (cls._db is None):
cls._initialise()
return cls._db
def close_db(cls):
if (cls._db is not None):
try:
cls._db.clo... |
class ConfigSetting():
_name = None
def __init__(self, default=ExplicitSettingRequired, description='No description supplied', dangerous=False, automatic=False):
self.description = description
self.default = default
self.dangerous = dangerous
self.automatic = automatic
def __... |
def _helper_runningmeanstd():
comm = MPI.COMM_WORLD
np.random.seed(0)
for (triple, axis) in [((np.random.randn(3), np.random.randn(4), np.random.randn(5)), 0), ((np.random.randn(3, 2), np.random.randn(4, 2), np.random.randn(5, 2)), 0), ((np.random.randn(2, 3), np.random.randn(2, 4), np.random.randn(2, 4)), ... |
class CharBiLSTM(nn.Module):
def __init__(self, char2idx, chars, char_emb_size, charlstm_hidden_dim, dropout=0.5):
super(CharBiLSTM, self).__init__()
print('[Info] Building character-level LSTM')
self.char_emb_size = char_emb_size
self.char2idx = char2idx
self.chars = chars
... |
def on_key_press(symbol, modifiers):
if (symbol == pyglet.window.key.SPACE):
if timer.running:
timer.running = False
elif (timer.time > 0):
timer.reset()
else:
timer.running = True
elif (symbol == pyglet.window.key.ESCAPE):
window.close() |
def test_scalar_creator_helper():
default = scalar()
assert (default.type.dtype == config.floatX)
assert (default.type.ndim == 0)
assert (default.type.shape == ())
assert (default.name is None)
custom = scalar(name='custom', dtype='int64')
assert (custom.dtype == 'int64')
assert (custom.... |
_config
def test_max_size_hint_no_flag(xmanager, conn):
w = None
def size_hints():
nonlocal w
w = conn.create_window(0, 0, 100, 100)
hints = ([0] * 18)
hints[7] = hints[8] = 100
w.set_property('WM_NORMAL_HINTS', hints, type='WM_SIZE_HINTS', format=32)
w.map()
... |
.end_to_end()
def test_error_when_hook_module_is_no_iterable(tmp_path):
tmp_path.joinpath('pyproject.toml').write_text("[tool.pytask.ini_options]\nhook_module = 'hooks'")
result = subprocess.run(('pytask', 'build', '--help'), cwd=tmp_path, capture_output=True)
assert (result.returncode == ExitCode.CONFIGURA... |
def main_worker(gpu, args):
args.gpu = gpu
args.rank = gpu
print(f'Process Launching at GPU {gpu}')
if args.distributed:
torch.cuda.set_device(args.gpu)
dist.init_process_group(backend='nccl')
print(f'Building train loader at GPU {gpu}')
train_loader = get_loader(args, split=args... |
class VoxelGenerator():
def __init__(self, voxel_size, point_cloud_range, max_num_points, max_voxels=20000):
point_cloud_range = np.array(point_cloud_range, dtype=np.float32)
voxel_size = np.array(voxel_size, dtype=np.float32)
grid_size = ((point_cloud_range[3:] - point_cloud_range[:3]) / vo... |
class Append(COp):
__props__ = ('inplace',)
def __init__(self, inplace=False):
self.inplace = inplace
if self.inplace:
self.destroy_map = {0: [0]}
else:
self.view_map = {0: [0]}
def make_node(self, x, toAppend):
assert isinstance(x.type, TypedListType)... |
_test
def test_clone_functional_model():
val_a = np.random.random((10, 4))
val_b = np.random.random((10, 4))
val_out = np.random.random((10, 4))
input_a = keras.Input(shape=(4,))
input_b = keras.Input(shape=(4,))
dense_1 = keras.layers.Dense(4)
dense_2 = keras.layers.Dense(4)
x_a = dense... |
def fixture_path(test_path):
test_path.makepyfile(test_classes='\n import pytest\n\n class Test1:\n .order("last")\n def test_two(self):\n assert True\n\n .order("first")\n def test_one(self):\n a... |
def _get_attributes(element):
properties = {}
for (attrib_name, val) in element.attrib.items():
if attrib_name.endswith('_LONG'):
val = six.integer_types[(- 1)](val)
attrib_name = attrib_name[:(- 5)]
else:
val = _un_escape_specials(val)
_extract_proper... |
def _get_package_bin_dir_app_paths(venv: Venv, package_info: PackageInfo, venv_bin_path: Path, local_bin_dir: Path) -> Set[Path]:
suffix = package_info.suffix
apps = []
if package_info.include_apps:
apps += package_info.apps
if package_info.include_dependencies:
apps += package_info.apps... |
def test_bn_reestimation():
tf.keras.backend.clear_session()
np.random.seed(0)
input_data = np.random.randn(1024, 32, 32, 3).astype(np.float32)
batch_size = 4
dataset = tf.data.Dataset.from_tensor_slices(input_data)
dataset = dataset.batch(batch_size=batch_size)
dummy_inputs = np.random.rand... |
class RegressionModelConfig(PretrainedConfig):
def __init__(self, a=0, b=0, double_output=False, random_torch=True, **kwargs):
super().__init__(**kwargs)
self.a = a
self.b = b
self.double_output = double_output
self.random_torch = random_torch
self.hidden_size = 1 |
_model('model_parallel_transformer_lm')
class ModelParallelTransformerLanguageModel(TransformerLanguageModel):
def build_model(cls, args, task):
if (not has_megatron_submodule):
raise ImportError('\n\nPlease install the megatron submodule:\n\n git submodule update --init fairseq/model_parallel/... |
class TextInputAdapter(ObjectBlockView):
def __init__(self, obj, container, x=10, y=10, *args, **kwargs):
ObjectBlockView.__init__(self, obj, container, *args, x=10, y=10, **kwargs)
txt = gui.TextInput()
ofbv = ObjectFunctionBlockView(self.reference_object, txt.get_value, 'get_value', 'get_v... |
def tensor_to_PIL(image_tensor, pixel_min=(- 1), pixel_max=1):
image_tensor = image_tensor.cpu()
if ((pixel_min != 0) or (pixel_max != 1)):
image_tensor = ((image_tensor - pixel_min) / (pixel_max - pixel_min))
image_tensor.clamp_(min=0, max=1)
to_pil = torchvision.transforms.functional.to_pil_im... |
class CloudGuruLectureLectureAssets(object):
def __init__(self, parent):
self._extension = None
self._mediatype = None
self._url = None
self._parent = parent
self._title = None
self._filename = None
self._fsize = None
self._active = False
def __rep... |
def test__torque_driven_ocp__maximize_predicted_height_CoM():
from bioptim.examples.torque_driven_ocp import maximize_predicted_height_CoM as ocp_module
bioptim_folder = os.path.dirname(ocp_module.__file__)
ocp_module.prepare_ocp(biorbd_model_path=(bioptim_folder + '/models/2segments_4dof_2contacts.bioMod')... |
.parametrize('old_version, new_version, changed', [(None, '5.12.1', False), ('5.12.1', '5.12.1', False), ('5.12.2', '5.12.1', True), ('5.12.1', '5.12.2', True), ('5.13.0', '5.12.2', True), ('5.12.2', '5.13.0', True)])
def test_qt_version_changed(state_writer, monkeypatch, old_version, new_version, changed):
monkeyp... |
def get_future_names(packages: List[Package], underlined: bool, job_set: taskhandle.BaseJobSet) -> Generator[(Future, None, None)]:
with ProcessPoolExecutor() as executor:
for package in packages:
for module in get_files(package, underlined):
job_set.started_job(module.modname)
... |
.parametrize('solver', [pytest.param(_make_se, id='SESolver'), pytest.param(_make_me, id='MESolver'), pytest.param(_make_br, id='BRSolver')])
def testPropSolver(solver):
a = destroy(5)
H = (a.dag() * a)
U = Propagator(solver(H, a))
c_ops = []
if (solver is not _make_se):
c_ops = [a]
asse... |
('multistep-stage')
def multistep_stage(stage, spec):
log.info('scheduling multistep stage with spec:\n%s', spec)
log.debug('selecting parameters')
parameters = {k: select_parameter(stage.view, v) for (k, v) in get_parameters(spec['parameters']).items()}
log.info('scattering')
singlesteppars = scatt... |
def get_solcast_forecast(latitude, longitude, api_key, map_variables=True, **kwargs):
params = dict(latitude=latitude, longitude=longitude, format='json', **kwargs)
data = _get_solcast(endpoint='forecast/radiation_and_weather', params=params, api_key=api_key, map_variables=map_variables)
return (data, {'lat... |
def _ssim(img1, img2, window, window_size, channel, size_average=True, mask=None):
mu1 = F.conv2d(img1, window, padding=(window_size // 2), groups=channel)
mu2 = F.conv2d(img2, window, padding=(window_size // 2), groups=channel)
mu1_sq = mu1.pow(2)
mu2_sq = mu2.pow(2)
mu1_mu2 = (mu1 * mu2)
sigma... |
class TestCals(unittest.TestCase):
def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
self._qubits = [0, 2]
self._controls = [1, 3]
self._maxrep = 10
self._circs = []
def run_sim(self, noise=None):
backend = qiskit.Aer.get_backe... |
_cache
def read_json_then_binary(game: RandovaniaGame) -> tuple[(Path, dict)]:
dir_path = game.data_path.joinpath('logic_database')
if dir_path.exists():
return (dir_path, data_reader.read_split_file(dir_path))
json_path = dir_path.joinpath(f'{game.value}.json')
if json_path.exists():
wi... |
class PdfFormEnv(pdfium_i.AutoCloseable):
def __init__(self, raw, config, pdf):
(self.raw, self.config, self.pdf) = (raw, config, pdf)
super().__init__(PdfFormEnv._close_impl, self.config, self.pdf)
def parent(self):
return self.pdf
def _close_impl(raw, config, pdf):
pdfium_c... |
class ConvNoDepthwiseLayerSelector(LayerSelector):
def select(self, layer_db: LayerDatabase, modules_to_ignore: List[tf.keras.layers.Layer]):
selected_layers = []
for layer in layer_db:
if (layer.module in modules_to_ignore):
continue
if (isinstance(layer.modu... |
def _add_realm_args(parser):
group = parser.add_argument_group(title='realm')
group.add_argument('--ict-head-size', type=int, default=None, help='Size of block embeddings to be used in ICT and REALM (paper default: 128)')
group.add_argument('--ict-load', type=str, default=None, help='Directory containing an... |
class WMS_NASA_GIBS(WMSBase):
layer_prefix = 'NASA_GIBS_'
name = 'NASA_GIBS'
def __init__(self, m=None):
self.m = m
if (self.m.get_crs(3857) == m.crs_plot):
self.usewms = self.m.add_wms.NASA_GIBS.EPSG_3857
elif (self.m.get_crs(3031) == m.crs_plot):
self.usewms... |
class CookieJar():
def __init__(self, pluginname, account=None):
self.cookies = {}
self.plugin = pluginname
self.account = account
def add_cookies(self, clist):
for c in clist:
name = c.split('\t')[5]
self.cookies[name] = c
def get_cookies(self):
... |
class DebertaTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
model_input_names = ['input_ids', 'attention_mask', 'token_type_ids']
def __init__(self, vocab_fil... |
class TestSimpleSearcher():
__test__ = False
def __init__(self):
self.query_text = np.random.random(text_vector_size).tolist()
self.query_image = np.random.random(image_vector_size).tolist()
self.query_code = np.random.random(code_vector_size).tolist()
def simple_search_text(self, cl... |
class DenseConv(nn.Module):
def __init__(self, inplanes, planes, kernel_size=3, stride=1, dilation=1, act_type='relu'):
super(DenseConv, self).__init__()
self.conv = nn.Conv2d(inplanes, planes, kernel_size=kernel_size, stride=stride, padding=get_same_padding(kernel_size, dilation), dilation=dilation... |
def test_title_normalization():
title = 'abcd'
body = '1234'
assert (util.normalize_title(title, body) == title)
title = '[2.7] bpo-29243: Fix Makefile with respect to --enable-optimizations ...'
body = '...(GH-1478)\r\n\r\nstuff'
expected = '[2.7] bpo-29243: Fix Makefile with respect to --enabl... |
def model_based_prob_help(A_k, trans_list, img_db_path, d, J, sigma_sq, n, i, k, alpha, xi):
X = get_image_db(img_db_path)
X_i = X[d['v']]
w_i = X[d['m']]
result = [None for _ in trans_list]
for (j, phi) in enumerate(trans_list):
ln_result = (ln_p_xo(A_k=A_k, phi=phi, X_i=X_i, w_i=w_i, J=J, ... |
_rewriter([IncSubtensor], inplace=True)
def local_inplace_setsubtensor(fgraph, node):
if (isinstance(node.op, IncSubtensor) and (not node.op.inplace)):
dta = node.op.destroyhandler_tolerate_aliased
new_op = node.op.__class__(node.op.idx_list, inplace=True, set_instead_of_inc=node.op.set_instead_of_i... |
def test_env_site_select_first(tmp_path: Path) -> None:
fallback = (tmp_path / 'fallback')
fallback.mkdir(parents=True)
site_packages = SitePackages(tmp_path, fallbacks=[fallback])
candidates = site_packages.make_candidates(Path('hello.txt'), writable_only=True)
assert (len(candidates) == 2)
ass... |
class TestNamedTuple(TestNameCheckVisitorBase):
_passes()
def test_args(self):
from typing import NamedTuple
class NT(NamedTuple):
field: int
class CustomNew():
def __new__(self, a: int) -> 'CustomNew':
return super().__new__(self)
def make... |
class NetworkBlock(nn.Module):
def __init__(self, nb_layers, in_planes, out_planes, block, stride, dropRate=0.0):
super(NetworkBlock, self).__init__()
self.layer = self._make_layer(block, in_planes, out_planes, nb_layers, stride, dropRate)
def _make_layer(self, block, in_planes, out_planes, nb_l... |
class RouterBackendTest(CreateDataMixin, TestCase):
def setUp(self):
self.router = BlockingRouter(apps=[], backends={})
def test_valid_backend_path(self):
backend = self.router.add_backend('backend', 'rapidsms.backends.base.BackendBase')
self.assertEqual(1, len(self.router.backends.keys(... |
class DatasetCatalog():
DATA_DIR = 'datasets'
DATASETS = {'kitti_train': {'root': 'kitti/training/'}, 'kitti_test': {'root': 'kitti/testing/'}}
def get(name):
if ('kitti' in name):
data_dir = DatasetCatalog.DATA_DIR
attrs = DatasetCatalog.DATASETS[name]
args = dic... |
.parametrize('url, valid, has_err_string', [(' True, False), ('', False, False), ('://', False, True)])
def test_raise_cmdexc_if_invalid(url, valid, has_err_string):
qurl = QUrl(url)
assert (qurl.isValid() == valid)
if valid:
urlutils.raise_cmdexc_if_invalid(qurl)
else:
assert (bool(qurl... |
class CallbackList(Callback):
def __init__(self, *args, with_header=True):
super(CallbackList, self).__init__(with_header=with_header)
assert all([issubclass(type(x), Callback) for x in args]), 'Callback inputs illegal: {}'.format(args)
self.callbacks = [callback for callback in args]
de... |
def test_consecutive_spacer(manager_nospawn):
config = GeomConf
config.screens = [libqtile.config.Screen(bottom=libqtile.bar.Bar([ExampleWidget(), libqtile.widget.Spacer(libqtile.bar.STRETCH), libqtile.widget.Spacer(libqtile.bar.STRETCH), ExampleWidget(), ExampleWidget(), libqtile.widget.Spacer(libqtile.bar.STR... |
class SnapshotsStub(object):
def __init__(self, channel):
self.Create = channel.unary_unary('/qdrant.Snapshots/Create', request_serializer=snapshots__service__pb2.CreateSnapshotRequest.SerializeToString, response_deserializer=snapshots__service__pb2.CreateSnapshotResponse.FromString)
self.List = cha... |
class GaussLayer(nn.Module):
def __init__(self, in_features, out_features, bias=True, sigma=10):
super().__init__()
self.sigma = sigma
self.linear = nn.Linear(in_features, out_features, bias=bias)
def forward(self, input):
return torch.exp((- ((self.sigma * self.linear(input)) **... |
.usefixtures('patched_df')
def test_df_always_visible(fake_qtile, fake_window):
df2 = df.DF(visible_on_warn=False)
fakebar = FakeBar([df2], window=fake_window)
df2._configure(fake_qtile, fakebar)
text = df2.poll()
assert (text == '/ (38G|83%)')
df2.draw()
assert (df2.layout.colour == df2.for... |
class TMP4UpdateParents64Bit(TestCase):
original = os.path.join(DATA_DIR, '64bit.mp4')
def setUp(self):
self.filename = get_temp_copy(self.original)
def test_update_parents(self):
with open(self.filename, 'rb') as fileobj:
atoms = Atoms(fileobj)
self.assertEqual(77, a... |
def density_fit(mf, auxbasis=None, mesh=None, with_df=None):
from pyscf.pbc.df import rsdf
if (with_df is None):
if (getattr(mf, 'kpts', None) is not None):
kpts = mf.kpts
else:
kpts = numpy.reshape(mf.kpt, (1, 3))
kpts = getattr(kpts, 'kpts', kpts)
with_d... |
class OrderedFactory(factory.Factory):
class Meta():
model = Ordered
_generation
def zzz(obj: Ordered, create: bool, val: Any, **kwargs: Any) -> None:
obj.value = 'zzz'
_generation
def aaa(obj: Ordered, create: bool, val: Any, **kwargs: Any) -> None:
obj.value = 'aaa' |
def test_requirement_lists_without_satisfied_resources(echoes_game_description, default_echoes_preset, echoes_game_patches):
def item(name):
return search.find_resource_info_with_long_name(echoes_game_description.resource_database.item, name)
state = echoes_game_description.game.generator.bootstrap.calc... |
class DetailedItinerariesComputer(BaseTravelTimeMatrixComputer):
COLUMNS = (['from_id', 'to_id', 'option'] + Trip.COLUMNS)
def __init__(self, transport_network, origins=None, destinations=None, snap_to_network=False, force_all_to_all=False, **kwargs):
super().__init__(transport_network, origins, destina... |
class MemoryFLACFileStream(UnclosedFLACFileStream):
def __init__(self, path, file):
self.file = file
self.file_size = 0
if (getattr(self.file, 'seek', None) and getattr(self.file, 'tell', None)):
self.seekable = True
self.file.seek(0, 2)
self.file_size = s... |
def create_vector(site_folder):
(site, num) = site_folder
file_dir = ((fold + '/') + site)
file = list(os.walk(file_dir))[0][(- 1)][:]
label = []
data = []
id = []
rows = {}
with open((fold + '/abide_preprocessed.csv'), newline='') as csvfile:
reader = csv.reader(csvfile, delimit... |
def test_dict_keyed_param_not_dotted():
param = 'ShipmentRequestDetails.PackageDimensions'
dict_from = {'Length': 5, 'Width': 5, 'Height': 5, 'Unit': 'inches'}
result = dict_keyed_param(param, dict_from)
expected = {'ShipmentRequestDetails.PackageDimensions.Length': 5, 'ShipmentRequestDetails.PackageDim... |
def test_output_argument_full_path(runner, mocker):
mocker.patch('products.vmware_cb_response.CbResponse._authenticate')
with runner.isolated_filesystem() as temp_dir:
full_output_path = os.path.join(temp_dir, 'full_output.csv')
runner.invoke(cli, ['--output', full_output_path])
assert o... |
def test_backward(n_times=1000):
device = torch.device('cuda')
input3d = torch.rand((1, 32, 32, 32, 32), requires_grad=True).to(device)
label = torch.rand((1, 32, 32, 32, 32), requires_grad=True).to(device)
deform_conv_pack = DeformConvPack(32, 32, 3, 1, 1).to(device)
optimizer = torch.optim.SGD(def... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.