code stringlengths 281 23.7M |
|---|
.parametrize('attn_method', ATTN_METHODS)
def test_performer_freezes_during_inference_time(attn_method):
kwargs = {'num_heads': 2, 'key_dim': 20, 'attention_method': attn_method, 'supports': 2}
(model, (x, y)) = get_fitted_model(**kwargs)
y1 = model.predict(x)
y2 = model.predict(x)
assert np.allclos... |
def estimated_steps_in_epoch(dataloader: Iterable[object], *, num_steps_completed: int, max_steps: Optional[int], max_steps_per_epoch: Optional[int]) -> float:
total = float('inf')
if isinstance(dataloader, Sized):
try:
total = len(dataloader)
except (NotImplementedError, TypeError):... |
class QueryAndGroup(nn.Module):
def __init__(self, radius, nsample, use_xyz=True):
super(QueryAndGroup, self).__init__()
(self.radius, self.nsample, self.use_xyz) = (radius, nsample, use_xyz)
def forward(self, xyz, new_xyz, features=None):
idx = ball_query(self.radius, self.nsample, xyz,... |
def calc_dino_div(dino, div, generated_images, split='train'):
dino_score = dino.img_to_img_similarity(reference_images, generated_images).item()
div_score = div.get_score(generated_images).item()
logs = {f'{split}_dino_score': dino_score, f'{split}_div_score': div_score}
return logs |
class TestChangeFilter():
(autouse=True)
def cleanup_globals(self, monkeypatch):
monkeypatch.setattr(config, 'change_filters', [])
.parametrize('option', ['foobar', 'tab', 'tabss', 'tabs.'])
def test_unknown_option(self, option):
cf = config.change_filter(option)
with pytest.rais... |
class SongsMenuPlugin(MenuItemPlugin):
plugin_single_song = None
plugin_song = None
plugin_songs = None
plugin_single_album = None
plugin_album = None
plugin_albums = None
def __init__(self, songs=None, library=None):
super().__init__()
self.__library = library
self._... |
class SwiGLUFFN(nn.Module):
def __init__(self, in_features: int, hidden_features: Optional[int]=None, out_features: Optional[int]=None, act_layer: Callable[(..., nn.Module)]=None, drop: float=0.0, bias: bool=True) -> None:
super().__init__()
out_features = (out_features or in_features)
hidde... |
def build_description_from_identifier(identifier: str) -> str:
(python_identifier, _, platform_identifier) = identifier.partition('-')
build_description = ''
python_interpreter = python_identifier[0:2]
python_version = python_identifier[2:]
if (python_interpreter == 'cp'):
build_description ... |
class noop_progress_bar(progress_bar):
def __init__(self, iterable, epoch=None, prefix=None):
super().__init__(iterable, epoch, prefix)
def __iter__(self):
for obj in self.iterable:
(yield obj)
def log(self, stats, tag=None, step=None):
pass
def print(self, stats, tag... |
def test_convert_dependencies() -> None:
package = ProjectPackage('foo', '1.2.3')
result = SdistBuilder.convert_dependencies(package, [Dependency('A', '^1.0'), Dependency('B', '~1.0'), Dependency('C', '1.2.3'), VCSDependency('D', 'git', ' Dependency('E', '^1.0'), Dependency('F', '^1.0,!=1.3')])
main = ['A>=... |
class ModuleWithRecordsAndDistance(ModuleWithRecords):
def __init__(self, distance=None, **kwargs):
super().__init__(**kwargs)
self.distance = (self.get_distance() if (distance is None) else distance)
def get_default_distance(self):
return LpDistance(p=2)
def get_distance(self):
... |
def _create_translator_gates_field(game: GameDescription, gate_assignment: dict[(NodeIdentifier, Requirement)]) -> list:
return [{'gate_index': game.region_list.node_by_identifier(identifier).extra['gate_index'], 'translator_index': translator_index_for_requirement(requirement)} for (identifier, requirement) in gat... |
class Docker(Module):
def __init__(self, name):
self._name = name
super().__init__()
def inspect(self):
output = self.check_output('docker inspect %s', self._name)
return json.loads(output)[0]
def is_running(self):
return self.inspect()['State']['Running']
def is_... |
def _print_configs(exp_dir, set_name, model_conf, train_conf, dataset_conf):
if (model_conf['n_bins'] != dataset_conf['n_bins']):
raise ValueError(('model and dataset n_bins not matched (%s != %s)' % (model_conf['n_bins'], dataset_conf['n_bins'])))
info(('Experiment Directory:\n\t%s' % str(exp_dir)))
... |
def get_errors_from_single_artifact(artifact_zip_path, job_links=None):
errors = []
failed_tests = []
job_name = None
with zipfile.ZipFile(artifact_zip_path) as z:
for filename in z.namelist():
if (not os.path.isdir(filename)):
if (filename in ['failures_line.txt', 's... |
def test_shared_dependencies_with_overlapping_constraints(root: ProjectPackage, provider: Provider, repo: Repository) -> None:
root.add_dependency(Factory.create_dependency('a', '1.0.0'))
root.add_dependency(Factory.create_dependency('b', '1.0.0'))
add_to_repo(repo, 'a', '1.0.0', deps={'shared': '>=2.0.0 <4... |
(frozen=True)
class Ge(AnnotatedTypesCheck):
value: Any
def predicate(self, value: Any) -> bool:
return (value >= self.value)
def is_compatible_metadata(self, metadata: AnnotatedTypesCheck) -> bool:
if isinstance(metadata, Gt):
return (metadata.value >= self.value)
elif i... |
_canonicalize
_specialize
_rewriter([Elemwise])
def local_exp_log(fgraph, node):
x = node.inputs[0]
if (not isinstance(node.op, Elemwise)):
return
if ((not x.owner) or (not isinstance(x.owner.op, Elemwise))):
return
prev_op = x.owner.op.scalar_op
node_op = node.op.scalar_op
if (i... |
_macro
def OpenJupyterNotebook(path=None, browser=False):
try:
if path:
if (not os.path.isabs(path)):
xl = xl_app(com_package='win32com')
wb = xl.ActiveWorkbook
if ((wb is not None) and wb.FullName and os.path.exists(wb.FullName)):
... |
class GroupBadgeManager(BadgeRenderMixin, CRUDMixin, RESTManager):
_path = '/groups/{group_id}/badges'
_obj_cls = GroupBadge
_from_parent_attrs = {'group_id': 'id'}
_create_attrs = RequiredOptional(required=('link_url', 'image_url'))
_update_attrs = RequiredOptional(optional=('link_url', 'image_url'... |
class TestSessionReports():
def test_collect_result(self, pytester: Pytester) -> None:
col = pytester.getmodulecol('\n def test_func1():\n pass\n class TestClass(object):\n pass\n ')
rep = runner.collect_one_node(col)
assert (not rep... |
def test_model_policy_gradient():
x0 = np.random.randn(5)
result = model_policy_gradient(sum_of_squares, x0, learning_rate=0.1, decay_rate=0.96, decay_steps=10, log_sigma_init=(- 6.0), max_iterations=120, batch_size=30, radius_coeff=3.0, warmup_steps=10, known_values=None)
np.testing.assert_allclose(result.... |
def _initial_iv_params(ivcurves, ee, voc, isc, rsh, nnsvth):
n = len(ivcurves['v_oc'])
io = np.ones(n)
iph = np.ones(n)
rs = np.ones(n)
for j in range(n):
if (rsh[j] > 0):
(volt, curr) = rectify_iv_curve(ivcurves['v'][j], ivcurves['i'][j])
io[j] = ((isc[j] - (voc[j] /... |
def read_file():
global list
global sequence_num
global sigmasize
global filename
f = open(filename)
sequence_num = 0
line = f.readline()
while line:
list.append(line)
sequence_num = (sequence_num + 1)
line = f.readline()
f.close()
print(sequence_num) |
def main(args):
wav_scp = codecs.open((Path(args.path) / 'wav.scp'), 'r', 'utf-8')
textgrid_flist = codecs.open((Path(args.path) / 'textgrid.flist'), 'r', 'utf-8')
utt2textgrid = {}
for line in textgrid_flist:
lines = line.strip().split(' ')
path = Path(lines[1])
uttid = lines[0]... |
class ACCESS_ALLOWED_ACE(ACE):
def __init__(self):
self.AceType = ACEType.ACCESS_ALLOWED_ACE_TYPE
self.AceFlags = None
self.AceSize = 0
self.Mask = None
self.Sid = None
self.sd_object_type = None
def from_buffer(buff, sd_object_type=None):
ace = ACCESS_ALL... |
def get_md_entry(DB, entry, add_comments=True):
md_str = '\n'
md_str += '- '
venue = ''
year = ''
if ('booktitle' in entry.keys()):
venue = entry['booktitle'].replace('Proceedings of ', '')
if ('journal' in entry.keys()):
venue += entry['journal'].replace('{', '').replace('}', ''... |
def set_tensor(module: 'torch.nn.Module', name: str, tensor: torch.Tensor) -> None:
if (name in module._parameters):
del module._parameters[name]
was_buffer = (name in module._buffers)
if was_buffer:
del module._buffers[name]
if isinstance(tensor, nn.Parameter):
module.__dict__.p... |
def info(filepath: Union[(str, Path)]) -> Dict[(str, Union[(str, Number)])]:
info_dictionary = {'channels': channels(filepath), 'sample_rate': sample_rate(filepath), 'bitdepth': bitdepth(filepath), 'bitrate': bitrate(filepath), 'duration': duration(filepath), 'num_samples': num_samples(filepath), 'encoding': encodi... |
class RealtimeHandler(EventsDemoHandler):
.coroutine
def get(self):
url = f'{options.admin_endpoint_base}/events/1/events/realtime/get'
params = {'company_id': options.company_id, 'cursor': self.next_cursor()}
response = requests.request('GET', url, headers=self.authorized_headers(), par... |
def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, loss_scaler, max_norm: float=0, model_ema: Optional[ModelEma]=None, mixup_fn: Optional[Mixup]=None, log_writer=None, wandb_logger=None, start_steps=None, lr_... |
def save_val_samples_funieGAN(samples_dir, gen_imgs, step, N_samples=3, N_ims=3):
row = N_samples
col = N_ims
titles = ['Input', 'Generated', 'Original']
(fig, axs) = plt.subplots(row, col)
cnt = 0
for j in range(col):
for i in range(row):
axs[(i, j)].imshow(gen_imgs[cnt])
... |
class A():
is_an_a: ClassVar[bool] = True
not_assigned_to: ClassVar[str]
def __init__(self):
self.instance_var: bool = True
async def async_method(self, wait: bool) -> int:
if wait:
(await asyncio.sleep(1))
return 5
def my_prop(self) -> str:
return 'prop'
... |
('/api/conversations/get_conversation_list', methods=['POST'])
def get_conversation_list() -> Response:
request_json = request.get_json()
user_id = request_json.pop('user_id', DEFAULT_USER_ID)
conversations = []
try:
db = get_user_conversation_storage()
conversation_list = db.conversatio... |
def _setup_single_view_dispatcher_route(constructor: ComponentConstructor, options: Options) -> _RouteHandlerSpecs:
return [(f'{STREAM_PATH}/(.*)', ModelStreamHandler, {'component_constructor': constructor, 'url_prefix': options.url_prefix}), (str(STREAM_PATH), ModelStreamHandler, {'component_constructor': construc... |
class XppLexer(RegexLexer):
name = 'X++'
url = '
aliases = ['xpp', 'x++']
filenames = ['*.xpp']
version_added = '2.15'
flags = re.MULTILINE
XPP_CHARS = ((((('?(?:_|[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl')) + '])') + '[^') + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl', 'Nd... |
class WassersteinUpdater(WassersteinUpdaterFramework):
def __init__(self, *args, **kwargs):
super(WassersteinUpdater, self).__init__(*args, **kwargs)
def g_loss(self, errG):
chainer.report({'loss': errG}, self.G)
return errG
def update_d(self, optimizer):
batch = self.get_ite... |
def test_poetry_with_supplemental_source(fixture_dir: FixtureDirGetter, with_simple_keyring: None) -> None:
io = BufferedIO()
poetry = Factory().create_poetry(fixture_dir('with_supplemental_source'), io=io)
assert poetry.pool.has_repository('PyPI')
assert (poetry.pool.get_priority('PyPI') is Priority.DE... |
def import_modules_from_strings(imports, allow_failed_imports=False):
if (not imports):
return
single_import = False
if isinstance(imports, str):
single_import = True
imports = [imports]
if (not isinstance(imports, list)):
raise TypeError(f'custom_imports must be a list b... |
class TestCombineValidSubsets(unittest.TestCase):
def _train(self, extra_flags):
with self.assertLogs() as logs:
with tempfile.TemporaryDirectory('test_transformer_lm') as data_dir:
create_dummy_data(data_dir, num_examples=20)
preprocess_lm_data(data_dir)
... |
class TestCRLReason():
def test_invalid_reason_flags(self):
with pytest.raises(TypeError):
x509.CRLReason('notareason')
def test_eq(self):
reason1 = x509.CRLReason(x509.ReasonFlags.unspecified)
reason2 = x509.CRLReason(x509.ReasonFlags.unspecified)
assert (reason1 == ... |
class Description(sa.Attributes):
('Description')
(rus.nothing)
def __init__(self):
self._attributes_extensible(True)
self._attributes_camelcasing(True)
self._attributes_register(EXECUTABLE, None, sa.STRING, sa.SCALAR, sa.WRITEABLE)
self._attributes_register(PRE_EXEC, None, s... |
def make_layers(cfg, batch_norm=False):
layers = list()
in_channels = 3
for v in cfg:
if (v == 'M'):
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
else:
conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
if batch_norm:
layers ... |
def get_rpt_sections_details(rpt_path):
from swmmio.defs import RPT_OBJECTS
found_sects = OrderedDict()
rpt_headers = RPT_OBJECTS.copy()
meta_data = get_rpt_metadata(rpt_path)
swmm_version = meta_data['swmm_version']
for version in SWMM5_VERSION:
version_value = float(version)
rp... |
def test_out_bounds(zarr_dataset: ChunkedDataset, cfg: dict) -> None:
gen_partial = get_partial(cfg, 0, 10, 0.1)
data = gen_partial(state_index=0, frames=np.asarray(zarr_dataset.frames[90:96]), agents=zarr_dataset.agents, tl_faces=np.zeros(0), selected_track_id=None)
assert (bool(np.all(data['target_availab... |
def test_default_both(hatch, helpers, temp_dir, config_file):
config_file.model.template.plugins['default']['tests'] = False
config_file.save()
project_name = 'My.App'
with temp_dir.as_cwd():
result = hatch('new', project_name)
assert (result.exit_code == 0), result.output
project_path =... |
def wrap_function_to_error_out_if_called_directly(function: FixtureFunction, fixture_marker: 'FixtureFunctionMarker') -> FixtureFunction:
message = 'Fixture "{name}" called directly. Fixtures are not meant to be called directly,\nbut are created automatically when test functions request them as parameters.\nSee fo... |
class DeiTFeatureExtractor(FeatureExtractionMixin, ImageFeatureExtractionMixin):
model_input_names = ['pixel_values']
def __init__(self, do_resize=True, size=256, resample=Image.BICUBIC, do_center_crop=True, crop_size=224, do_normalize=True, image_mean=None, image_std=None, **kwargs):
super().__init__(*... |
class SelfImportVisitor(ImportInfoVisitor):
def __init__(self, project, current_folder, resource):
self.project = project
self.folder = current_folder
self.resource = resource
self.to_be_fixed = set()
self.to_be_renamed = set()
self.context = importinfo.ImportContext(... |
class OpenWithFileDescriptorTest(FakeFileOpenTestBase):
def test_open_with_file_descriptor(self):
file_path = self.make_path('this', 'file')
self.create_file(file_path)
fd = self.os.open(file_path, os.O_CREAT)
self.assertEqual(fd, self.open(fd, 'r').fileno())
def test_closefd_wit... |
.xfail(reason='BigQuery emulator does not support REQUIRED fields')
def test_required_types(client):
client = BigQueryClient(client)
recap_schema = client.schema('test_project', 'test_dataset', 'test_table_required')
recap_fields = recap_schema.fields
assert (recap_fields[0] == StringType(name='test_str... |
class MixStyle(nn.Module):
def __init__(self, p=0.5, alpha=0.1, eps=1e-06, mix='random'):
super().__init__()
self.p = p
self.beta = torch.distributions.Beta(alpha, alpha)
self.eps = eps
self.alpha = alpha
self.mix = mix
self._activated = True
def __repr__(... |
def a1_a2_calculation(r, rdot, omega, D, M, eta):
assert (type(r) == list), 'r should be a list.'
assert (type(rdot) == list), 'rdot should be a list.'
assert (type(omega) == list), 'omega should be a list.'
assert (type(D) == float), 'D should be a float.'
assert (type(M) == float), 'M should be a ... |
class GroupAccumulator(Accumulator):
def __init__(self):
super().__init__()
self._groups = []
def state(self) -> Dict[(str, torch.Tensor)]:
state = super().state
state.update({'groups': self.groups})
return state
def update(self, embeddings: torch.Tensor, groups: torc... |
class BeforeClose(StatelessRule):
def __init__(self, offset=None, **kwargs):
self.offset = _build_offset(offset, kwargs, datetime.timedelta(minutes=1))
self._period_start = None
self._period_close = None
self._period_end = None
self._one_minute = datetime.timedelta(minutes=1)... |
def generate_object_struct(cl: ClassIR, emitter: Emitter) -> None:
seen_attrs: set[tuple[(str, RType)]] = set()
lines: list[str] = []
lines += ['typedef struct {', 'PyObject_HEAD', 'CPyVTableItem *vtable;']
if (cl.has_method('__call__') and emitter.use_vectorcall()):
lines.append('vectorcallfunc... |
def parse_args():
parser = argparse.ArgumentParser(description='Train a detector')
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')
pa... |
def fix_cache_order(item: nodes.Item, argkeys_cache: Dict[(Scope, Dict[(nodes.Item, Dict[(FixtureArgKey, None)])])], items_by_argkey: Dict[(Scope, Dict[(FixtureArgKey, 'Deque[nodes.Item]')])]) -> None:
for scope in HIGH_SCOPES:
for key in argkeys_cache[scope].get(item, []):
items_by_argkey[scope... |
def is_transaction_expired(transaction: ContractSendEvent, block_number: BlockNumber) -> bool:
is_update_expired = (isinstance(transaction, ContractSendChannelUpdateTransfer) and (transaction.expiration < block_number))
if is_update_expired:
return True
is_secret_register_expired = (isinstance(trans... |
def find_locales(name, dir='locale'):
locale_files = []
for walk in os.walk(((('./' + name) + '/') + dir)):
(path, dirs, files) = walk
path = path[(len(name) + 3):]
for file in files:
if (file[(- 3):] == '.mo'):
locale_files.append(os.path.join(path, file))
... |
def will_change(*, reason, version):
add_warning = _deprecated(reason=reason, version=version, category=SKCriteriaFutureWarning, action='once')
def _dec(func):
decorated_func = add_warning(func)
decorated_func.__doc__ = add_sphinx_deprecated_directive(func.__doc__, reason=reason, version=version... |
.parametrize('case', [CaseBits32ClosureConstruct, CaseBits32ArrayClosureConstruct, CaseTwoUpblksSliceComp, CaseTwoUpblksFreevarsComp])
def test_generic_behavioral_L1(case):
m = case.DUT()
m.elaborate()
tr = mk_TestBehavioralTranslator(BehavioralTranslatorL1)(m)
tr.clear(m)
tr.translate_behavioral(m)... |
class FairseqMultiModel(BaseFairseqModel):
def __init__(self, encoders, decoders):
super().__init__()
assert (encoders.keys() == decoders.keys())
self.keys = list(encoders.keys())
for key in self.keys:
check_type(encoders[key], FairseqEncoder)
check_type(decod... |
class EarthMoverDistanceFunction(torch.autograd.Function):
def forward(ctx, xyz1, xyz2):
xyz1 = xyz1.contiguous()
xyz2 = xyz2.contiguous()
assert (xyz1.is_cuda and xyz2.is_cuda), 'Only support cuda currently.'
match = emd_cuda.approxmatch_forward(xyz1, xyz2)
cost = emd_cuda.m... |
class SNMPRawCollector(parent_SNMPCollector):
def process_config(self):
super(SNMPRawCollector, self).process_config()
self.skip_list = []
def get_default_config(self):
default_config = super(SNMPRawCollector, self).get_default_config()
default_config.update({'oids': {}, 'path_pr... |
_fixtures(WebFixture, LayoutScenarios)
def test_navbar_can_have_layout(web_fixture, layout_scenarios):
fixture = layout_scenarios
widget = Navbar(web_fixture.view).use_layout(fixture.layout)
[navbar] = widget.children
all_classes = ['fixed-bottom', 'fixed-top', 'sticky-top']
if fixture.expected_css_... |
def get_interpreters(minimumVersion=None):
if sys.platform.startswith('win'):
pythons = _get_interpreters_win()
else:
pythons = _get_interpreters_posix()
pythons = set([PythonInterpreter(p) for p in pythons])
condas = set([PythonInterpreter(p) for p in _get_interpreters_conda()])
rel... |
class Logger():
fold_mode: str
colors_enabled: bool
unicode_enabled: bool
active_build_identifier: (str | None) = None
build_start_time: (float | None) = None
step_start_time: (float | None) = None
active_fold_group_name: (str | None) = None
def __init__(self) -> None:
if ((sys.p... |
(name='plugin.vote', signature=['array', 'integer', 'integer'], login_required=False)
def plugin_vote(plugin_id, vote, **kwargs):
try:
request = kwargs.get('request')
except:
msg = _('Invalid request.')
raise ValidationError(msg)
try:
plugin = Plugin.objects.get(pk=plugin_id)... |
class TestBuildingMenu(CommandTest):
def setUp(self):
super(TestBuildingMenu, self).setUp()
self.menu = BuildingMenu(caller=self.char1, obj=self.room1, title='test')
self.menu.add_choice('title', key='t', attr='key')
def test_quit(self):
self.assertFalse(self.char1.cmdset.has('bu... |
def test_jsonifability():
res = TwitterDictResponse({'a': 'b'})
p = json.dumps(res)
res2 = json.loads(p)
assert (res == res2)
assert (res2['a'] == 'b')
res = TwitterListResponse([1, 2, 3])
p = json.dumps(res)
res2 = json.loads(p)
assert (res == res2)
assert (res2[2] == 3) |
def get_articulation_state(art):
root_link = art.get_links()[0]
base_pose = root_link.get_pose()
base_vel = root_link.get_velocity()
base_ang_vel = root_link.get_angular_velocity()
qpos = art.get_qpos()
qvel = art.get_qvel()
return (base_pose.p, base_pose.q, base_vel, base_ang_vel, qpos, qve... |
class TrainTest(unittest.TestCase):
def _run_train(cls) -> None:
train(embedding_dim=16, num_iterations=10)
_if_asan
def test_train_function(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
lc = LaunchConfig(min_nodes=1, max_nodes=1, nproc_per_node=2, run_id=str(uuid.... |
class TestOCSPEdDSA():
.supported(only_if=(lambda backend: backend.ed25519_supported()), skip_message='Requires OpenSSL with Ed25519 support / OCSP')
def test_invalid_algorithm(self, backend):
builder = ocsp.OCSPResponseBuilder()
(cert, issuer) = _cert_and_issuer()
private_key = ed25519.... |
def extract_hyperparameters_from_trainer(trainer):
hyperparameters = {k: getattr(trainer.args, k) for k in _TRAINING_ARGS_KEYS}
if (trainer.args.parallel_mode not in [ParallelMode.NOT_PARALLEL, ParallelMode.NOT_DISTRIBUTED]):
hyperparameters['distributed_type'] = ('multi-GPU' if (trainer.args.parallel_m... |
def build_custom_optimizer(cfg: CfgNode, model: torch.nn.Module) -> torch.optim.Optimizer:
params: List[Dict[(str, Any)]] = []
memo: Set[torch.nn.parameter.Parameter] = set()
custom_multiplier_name = cfg.SOLVER.CUSTOM_MULTIPLIER_NAME
optimizer_type = cfg.SOLVER.OPTIMIZER
for (key, value) in model.na... |
class Gamma(Distribution):
def __init__(self, name, mean, stdv, input_type=None, startpoint=None):
if (input_type is None):
beta = (mean / (stdv ** 2))
alpha = ((mean ** 2) / (stdv ** 2))
else:
beta = mean
alpha = stdv
self.dist_obj = gamma(a=a... |
def import_CUHK03(dataset_dir, detected=False):
cuhk03_dir = os.path.join(dataset_dir, 'CUHK03')
if (not os.path.exists(cuhk03_dir)):
Print('Please Download the CUHK03 Dataset')
if (not detected):
cuhk03_dir = os.path.join(cuhk03_dir, 'labeled')
else:
cuhk03_dir = os.path.join(cu... |
def idx2data(batchgroup, x_data, x_char_data, answerData, lengthData):
x_minibatch = list()
y_minibatch = list()
xlen_minibatch = list()
x_char_minibatch = list()
for idx in batchgroup:
x_minibatch.append(x_data[idx][:])
y_minibatch.append(answerData[idx][:])
x_char_minibatch... |
def build_cpd_dawg(morph, cpd, min_word_freq):
words = [word for (word, fd) in cpd.items() if (fd.freqdist().N() >= min_word_freq)]
prob_data = filter((lambda rec: (not _all_the_same(rec[1]))), ((word, _tag_probabilities(morph, word, cpd)) for word in words))
dawg_data = (((word, tag), prob) for (word, prob... |
def write_file_to_zookeeper(zookeeper: KazooClient, source_file: BinaryIO, dest_path: str) -> bool:
logger.info('Writing to %s in ZooKeeper...', dest_path)
try:
(current_data, stat) = zookeeper.get(dest_path)
current_version = stat.version
except NoNodeError:
raise NodeDoesNotExistEr... |
def and_conditional_maps(m1: TypeMap, m2: TypeMap, use_meet: bool=False) -> TypeMap:
if ((m1 is None) or (m2 is None)):
return None
result = m2.copy()
m2_keys = {literal_hash(n2) for n2 in m2}
for n1 in m1:
if ((literal_hash(n1) not in m2_keys) or isinstance(get_proper_type(m1[n1]), AnyT... |
def get_config_from_root(root):
setup_cfg = os.path.join(root, 'setup.cfg')
parser = configparser.ConfigParser()
with open(setup_cfg, 'r') as cfg_file:
parser.read_file(cfg_file)
VCS = parser.get('versioneer', 'VCS')
section = parser['versioneer']
cfg = VersioneerConfig()
cfg.VCS = V... |
def qt_message_handler(msg_type: qtcore.QtMsgType, context: qtcore.QMessageLogContext, msg: Optional[str]) -> None:
qt_to_logging = {qtcore.QtMsgType.QtDebugMsg: logging.DEBUG, qtcore.QtMsgType.QtWarningMsg: logging.WARNING, qtcore.QtMsgType.QtCriticalMsg: logging.ERROR, qtcore.QtMsgType.QtFatalMsg: logging.CRITICA... |
class TemplateTagsTest(unittest.TestCase):
def test_iso_time_tag(self):
now = datetime.datetime(2014, 1, 1, 12, 0)
template = Template('{% load cms %}{% iso_time_tag now %}')
rendered = template.render(Context({'now': now}))
self.assertIn('<time datetime="2014-01-01T12:00:00"><span c... |
def str_q2b(text):
ustring = text
rstring = ''
for uchar in ustring:
inside_code = ord(uchar)
if (inside_code == 12288):
inside_code = 32
elif (65281 <= inside_code <= 65374):
inside_code -= 65248
rstring += chr(inside_code)
return rstring |
.skip(reason='web RTC is disabled')
.parametrize('matrix_server_count', [1])
.parametrize('number_of_transports', [2])
.parametrize('capabilities', [CapabilitiesConfig(web_rtc=True)])
def test_web_rtc_message_sync(matrix_transports):
(transport0, transport1) = matrix_transports
transport1_messages = set()
r... |
class TestApi():
def __init__(self):
self.apiex = APIExerciser.APIExerciser(None, True, 'TestUser', 'pwhere')
def test_login(self):
assert (self.apiex.api.login('crapp', 'wrong pw') is False)
def test_random(self):
for i in range(0, 100):
self.apiex.testAPI() |
def main(args):
model_save_path = preprocess(args)
data = load_data(args)
features = torch.FloatTensor(data.features)
labels = torch.LongTensor(data.labels)
if hasattr(torch, 'BoolTensor'):
train_mask = torch.BoolTensor(data.train_mask)
val_mask = torch.BoolTensor(data.val_mask)
... |
def subsample_labels(labels: torch.Tensor, num_samples: int, positive_fraction: float, bg_label: int):
positive = nonzero_tuple(((labels != (- 1)) & (labels != bg_label)))[0]
negative = nonzero_tuple((labels == bg_label))[0]
num_pos = int((num_samples * positive_fraction))
num_pos = min(positive.numel()... |
class EchoesHintDistributor(HintDistributor):
def num_joke_hints(self) -> int:
return 2
async def get_guaranteed_hints(self, patches: GamePatches, prefill: PreFillParams) -> list[HintTargetPrecision]:
def g(index, loc):
return (PickupIndex(index), PrecisionPair(loc, HintItemPrecision... |
def clean_folder(folder):
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
try:
if (os.path.isfile(file_path) or os.path.islink(file_path)):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_pa... |
class SAPM():
def setup(self):
set_weather_data(self)
if (Version(pvlib.__version__) >= Version('0.7.0')):
kwargs = pvlib.temperature.TEMPERATURE_MODEL_PARAMETERS['sapm']
kwargs = kwargs['open_rack_glass_glass']
self.sapm_cell_wrapper = partial(pvlib.temperature.s... |
class example_result(object):
__slots__ = ('success', 'exc', 'err')
def __init__(self, success=None, exc=None, err=None):
self.success = success
self.exc = exc
self.err = err
def read(self, iprot):
if ((iprot._fast_decode is not None) and isinstance(iprot.trans, TTransport.CR... |
_fixtures(WebFixture, DhtmlFixture)
def test_i18n_dhtml(web_fixture, dhtml_fixture):
class MainUI(UserInterface):
def assemble(self):
self.define_page(HTML5Page).use_layout(BasicPageLayout())
self.define_user_interface('/dhtml_ui', DhtmlUI, {'main_slot': 'main'}, name='test_ui', stat... |
class Stream(ctypes.Structure):
_fields_ = [('CR', ctypes.c_uint32), ('NDTR', ctypes.c_uint32), ('PAR', ctypes.c_uint32), ('M0AR', ctypes.c_uint32), ('M1AR', ctypes.c_uint32), ('FCR', ctypes.c_uint32)]
def enable(self):
return (self.CR & DMA_SxCR.EN)
def transfer_direction(self):
return (sel... |
class SparseManifestList(ManifestListInterface):
def __init__(self, manifest_bytes: Bytes, media_type, validate=False):
assert isinstance(manifest_bytes, Bytes)
self._payload = manifest_bytes
self._media_type = media_type
try:
self._parsed = json.loads(self._payload.as_un... |
def is_training_over_time_limit(extra_state: Dict[(str, Any)], stop_time: float) -> bool:
elapsed_hr = (((time.time() - extra_state['start_time']) + extra_state['previous_training_time']) / (60 * 60))
if ((stop_time >= 0) and (elapsed_hr > stop_time)):
print(f"Stopping training due to stop time limit of... |
def convertRadisToJSON(config_path_json, config_path_old=CONFIG_PATH_OLD):
config = get_user_config_configformat(config_path_old)
config_json = {}
for i in config.sections():
temp = {}
for j in config[i]:
if (j == 'path'):
if ('\n' in config[i][j]):
... |
class Config(NamedTuple):
args: Namespace
bench_once: Callable[([Client, Namespace, Optional[str]], Any)]
create_tidy_results: Callable[([Namespace, np.ndarray, List[Any]], Tuple[(pd.DataFrame, np.ndarray)])]
pretty_print_results: Callable[([Namespace, Mapping[(str, int)], np.ndarray, List[Any]], None)] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.