code stringlengths 281 23.7M |
|---|
class TestRecordBatchTables(unittest.TestCase):
def setUp(self) -> None:
self.column_names = ['pk', 'sk']
def test_single_table_with_batches_and_remainder(self):
min_records_batch = 8
bt = RecordBatchTables(min_records_batch)
col1 = pa.array([i for i in range(10)])
col2 =... |
.functions
def test_deconcatenate_column_string_no_sep(dataframe):
with pytest.raises(ValueError):
df_orig = dataframe.concatenate_columns(column_names=['a', 'decorated-elephant'], sep='-', new_column_name='index')
df = df_orig.deconcatenate_column(column_name='index', new_column_names=['A', 'B']) |
class Merge(nn.Module):
def __init__(self, block_spec, norm_cfg, alpha, filter_size_scale):
super(Merge, self).__init__()
out_channels = int((FILTER_SIZE_MAP[block_spec.level] * filter_size_scale))
if (block_spec.block_fn == Bottleneck):
out_channels *= 4
self.block = blo... |
class NeuralBuilder(nn.Module):
def __init__(self, gnp):
super(NeuralBuilder, self).__init__()
self.gnp = gnp
def get_param_g(self):
return self.gnp
def generate_batches(self, train_insts, batch_size):
pass
def build_nn_graph(self, instance):
pass
def build_nn... |
def main(input_file, enable_trace=False):
ql = Qiling(['./arm_fuzz'], '../../rootfs/arm_qnx', console=enable_trace)
ql.os.stdin = pipe.SimpleInStream(sys.stdin.fileno())
if (not enable_trace):
ql.os.stdout = pipe.NullOutStream(sys.stdout.fileno())
ql.os.stderr = pipe.NullOutStream(sys.stderr... |
class TestTransformerEqualizer(unittest.TestCase):
def test_default(self):
tfm = new_transformer()
tfm.equalizer(500.0, 2, 3)
actual_args = tfm.effects
expected_args = ['equalizer', '500.000000', '2.000000q', '3.000000']
self.assertEqual(expected_args, actual_args)
ac... |
def attempt_distribution(factor, num, denum, out_type):
(pos_terms, neg_terms) = local_add_canonizer.get_num_denum(factor)
if ((len(pos_terms) == 1) and (not neg_terms)):
return (False, factor, num, denum)
pos_pairs = list(map(local_mul_canonizer.get_num_denum, pos_terms))
neg_pairs = list(map(l... |
class CreateTargetAssignerTest(tf.test.TestCase):
def test_create_target_assigner(self):
corners = [[0.0, 0.0, 1.0, 1.0]]
groundtruth = box_list.BoxList(tf.constant(corners))
priors = box_list.BoxList(tf.constant(corners))
prior_stddevs = tf.constant([[1.0, 1.0, 1.0, 1.0]])
p... |
def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments))
if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')):
(model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
(model_args, data_arg... |
(scope='function')
def pvwatts_dc_pvwatts_ac_faiman_temp_system():
module_parameters = {'pdc0': 220, 'gamma_pdc': (- 0.003)}
temp_model_params = {'u0': 25.0, 'u1': 6.84}
inverter_parameters = {'pdc0': 220, 'eta_inv_nom': 0.95}
system = PVSystem(surface_tilt=32.2, surface_azimuth=180, module_parameters=m... |
class py_dep(dep):
def __init__(self, name, pip_only=False):
self.pip_only = pip_only
super(py_dep, self).__init__(name)
def test(self):
remap = {'pil': 'PIL', 'gevent-websocket': 'geventwebsocket', 'flask-socketio': 'flask_socketio', 'flask-babel': 'flask_babel', 'python-socketio': 'soc... |
def save_checkpoint(state, is_best, checkpoint='checkpoints/', filename='checkpoint.pth.tar', snapshot=None):
if (not os.path.exists(checkpoint)):
os.makedirs(checkpoint)
filepath = os.path.join(checkpoint, filename)
torch.save(state, filepath)
if (snapshot and ((state.epoch % snapshot) == 0)):
... |
def test_has_dict():
value = HasDict(10, {uuid.UUID('-0000-1111-0000-'): 15}, [RandovaniaGame.BLANK], [None], {}, datetime.datetime(2019, 1, 3, 2, 50, tzinfo=datetime.UTC), N(2403, True), (60, RandovaniaGame.METROID_PRIME_ECHOES, 'foo'))
data = {'a': 10, 'b': {'-0000-1111-0000-': 15}, 'c': ['blank'], 'd': [None... |
('I assign {value} to font.{sub_super}script')
def when_I_assign_value_to_font_sub_super(context, value, sub_super):
font = context.font
name = {'sub': 'subscript', 'super': 'superscript'}[sub_super]
new_value = {'None': None, 'True': True, 'False': False}[value]
setattr(font, name, new_value) |
class L1_plus_perceptualLoss(nn.Module):
def __init__(self, lambda_L1, lambda_perceptual, perceptual_layers, gpu_ids, percep_is_l1):
super(L1_plus_perceptualLoss, self).__init__()
self.lambda_L1 = lambda_L1
self.lambda_perceptual = lambda_perceptual
self.gpu_ids = gpu_ids
sel... |
class MaskRCNNLossComputation(object):
def __init__(self, proposal_matcher, discretization_size):
self.proposal_matcher = proposal_matcher
self.discretization_size = discretization_size
def match_targets_to_proposals(self, proposal, target):
match_quality_matrix = boxlist_iou(target, pro... |
class ViltConfig(PretrainedConfig):
model_type = 'vilt'
def __init__(self, vocab_size=30522, type_vocab_size=2, modality_type_vocab_size=2, max_position_embeddings=40, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.0, attention_pro... |
def printalltokens(args):
printT('All tokens which are accessible from current thread:')
if (('currentpidonly' in args) and (args['currentpidonly'] == True)):
args['pid'] = GetCurrentProcessId()
imp = Impersonate()
if (args['filter'] == ''):
imp.printAllTokensAccessible(targetPID=args['p... |
def gen_train_facts(data_file_name, truth_dir):
fact_file_name = data_file_name[data_file_name.find('train_'):]
fact_file_name = os.path.join(truth_dir, fact_file_name.replace('.json', '.fact'))
if os.path.exists(fact_file_name):
fact_in_train = set([])
triples = json.load(open(fact_file_nam... |
def main():
args = parse_args()
if (args.job_dir == ''):
args.job_dir = (get_shared_folder() / '%j')
executor = submitit.AutoExecutor(folder=args.job_dir, slurm_max_num_timeout=30)
num_gpus_per_node = args.ngpus
nodes = args.nodes
timeout_min = (args.timeout * 60)
partition = args.pa... |
class CRF(nn.Module):
def __init__(self, args, hidden_size: int, device: torch.device):
super(CRF, self).__init__()
self.modelname = 'crf'
self.hidden_size = hidden_size
self._crf = crf(args.tagger_classes, batch_first=True).to(device)
self._hidden2tag = Linear(self.hidden_si... |
def calc_gradient_penalty(x, y_pred):
gradients = torch.autograd.grad(outputs=y_pred, inputs=x, grad_outputs=torch.ones_like(y_pred), create_graph=True)[0]
gradients = gradients.flatten(start_dim=1)
grad_norm = gradients.norm(2, dim=1)
gradient_penalty = ((grad_norm - 1) ** 2).mean()
return gradient... |
def train(num_epochs, model, optimizer, train_loader, val_loader, fabric, accumulation_steps):
for epoch in range(num_epochs):
train_acc = torchmetrics.Accuracy(task='multiclass', num_classes=2).to(fabric.device)
model.train()
for (batch_idx, batch) in enumerate(train_loader):
mo... |
class Session():
def hascreds(cls, config):
return NotImplemented
def get_credential_options(self):
return NotImplemented
def from_foreign_session(session, cls=None):
if (not cls):
return DummySession()
else:
return cls(session)
def cls_from_path(p... |
class GSConv(nn.Module):
def __init__(self, c1, c2, k=1, s=1, g=1, act=True):
super().__init__()
c_ = (c2 // 2)
self.cv1 = Conv(c1, c_, k, s, None, g, act)
self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)
def forward(self, x):
x1 = self.cv1(x)
x2 = torch.cat((x1, self... |
class ArgumentGroup(object):
def __init__(self, parser, title, des):
self._group = parser.add_argument_group(title=title, description=des)
def add_arg(self, name, type, default, help, **kwargs):
type = (str2bool if (type == bool) else type)
self._group.add_argument(('--' + name), default... |
.supported(only_if=(lambda backend: backend.cipher_supported(algorithms._IDEAInternal((b'\x00' * 16)), modes.CFB((b'\x00' * 8)))), skip_message='Does not support IDEA CFB')
class TestIDEAModeCFB():
test_cfb = generate_encrypt_test(load_nist_vectors, os.path.join('ciphers', 'IDEA'), ['idea-cfb.txt'], (lambda key, **... |
def read_image(img_path):
got_img = False
if (not osp.exists(img_path)):
raise IOError('{} does not exist'.format(img_path))
while (not got_img):
try:
img = Image.open(img_path).convert('RGB')
got_img = True
except IOError:
print("IOError incurred ... |
def highs_solve_qp(P: Union[(np.ndarray, spa.csc_matrix)], q: np.ndarray, G: Optional[Union[(np.ndarray, spa.csc_matrix)]]=None, h: Optional[np.ndarray]=None, A: Optional[Union[(np.ndarray, spa.csc_matrix)]]=None, b: Optional[np.ndarray]=None, lb: Optional[np.ndarray]=None, ub: Optional[np.ndarray]=None, initvals: Opti... |
def test_push_pull_emoji_unicode(pusher, puller, unicode_emoji_images, liveserver_session, app_reloader):
credentials = ('devtable', 'password')
pusher.push(liveserver_session, 'devtable', 'newrepo', 'latest', unicode_emoji_images, credentials=credentials)
puller.pull(liveserver_session, 'devtable', 'newrep... |
def main():
args = parse_command_line_arguments()
if args.verbose:
logging.getLogger().setLevel(logging.DEBUG)
test_set = load_test_set(os.path.abspath(args.test_set_path))
results = Results(find_results_file(args), test_set)
if (args.command == 'run'):
run(test_set, results, only_pr... |
class ImageLogger(Callback):
def __init__(self, batch_frequency, max_images, clamp=True, increase_log_steps=True):
super().__init__()
self.batch_freq = batch_frequency
self.max_images = max_images
self.logger_log_images = {pl.loggers.WandbLogger: self._wandb, pl.loggers.TestTubeLogge... |
_datapipe('lines_to_paragraphs')
class ParagraphAggregatorIterDataPipe(IterDataPipe[Tuple[(str, str)]]):
def __init__(self, source_datapipe: IterDataPipe[Tuple[(str, T_co)]], joiner: Callable=_default_line_join) -> None:
self.source_datapipe: IterDataPipe[Tuple[(str, T_co)]] = source_datapipe
_check... |
def test_filter_by_type(graphql_client, user, conference_factory, submission_factory, mock_has_ticket):
graphql_client.force_login(user)
conference = conference_factory(submission_types=('talk', 'workshop'))
submission = submission_factory(conference=conference, custom_submission_type='talk')
submission... |
def test_inparchive(tmpdir, multiproc_backend):
workdir = os.path.join(str(tmpdir), 'workdir')
inputarchive = 'file://{}/tests/testspecs/dynamic_glob/inputs/three_files.zip'.format(os.path.abspath(os.curdir))
with steering_ctx(('local:' + workdir), 'workflow_frominit.yml', {'inputfiles': '*.txt'}, 'tests/te... |
class ClientTests(unittest.TestCase):
def test_make_batch(self):
transport = mock.Mock(spec=metrics.NullTransport)
client = metrics.Client(transport, 'namespace')
batch = client.batch()
self.assertIsInstance(batch, metrics.Batch)
self.assertEqual(batch.namespace, b'namespace'... |
def parse_arguments():
parser = ArgumentParser()
parser = add_experimental_args(parser)
parser.add_argument('--dataset', type=str, default='argoverse', help='Name of dataset to use')
parser.add_argument('--model-name', type=str, default='WIMP', help='Name of model to load')
(temp_args, _) = parser.p... |
class GithubBuildTrigger(BuildTriggerHandler):
def _get_client(self):
return Github(base_url=github_trigger.api_endpoint(), login_or_token=(self.auth_token if self.auth_token else github_trigger.client_id()), password=(None if self.auth_token else github_trigger.client_secret()), timeout=5)
def service_... |
class ID3v1Tags(TestCase):
def setUp(self):
self.filename = os.path.join(DATA_DIR, 'silence-44-s-v1.mp3')
self.id3 = ID3(self.filename)
def test_album(self):
self.assertEquals('Quod Libet Test Data', self.id3['TALB'])
def test_genre(self):
self.assertEquals('Darkwave', self.i... |
def get_extensions():
extension = CppExtension
extra_link_args = []
extra_compile_args = {'cxx': ['-O3', '-std=c++17', '-fdiagnostics-color=always']}
debug_mode = (os.getenv('DEBUG', '0') == '1')
if debug_mode:
print('Compiling in debug mode')
extra_compile_args = {'cxx': ['-O0', '-f... |
class _RoIPooling(Module):
def __init__(self, pooled_height, pooled_width, spatial_scale):
super(_RoIPooling, self).__init__()
self.pooled_width = int(pooled_width)
self.pooled_height = int(pooled_height)
self.spatial_scale = float(spatial_scale)
def forward(self, features, rois)... |
def command_dlow(command, args):
def setup(parser):
add_source_options(parser)
add_double_options(parser)
add_filter_options(parser)
parser.remove_option('--highpass')
parser.remove_option('--highpass_rel')
parser.set_defaults(rel_lowpass_frequency=0.25)
(parser, ... |
class GdbClick(sublime_plugin.TextCommand):
def run(self, edit):
if (not is_running()):
return
(row, col) = self.view.rowcol(self.view.sel()[0].a)
if (gdb_variables_view.is_open() and (self.view.id() == gdb_variables_view.get_view().id())):
gdb_variables_view.expand_c... |
('mmocr.utils.ocr.init_detector')
('mmocr.utils.ocr.build_detector')
('mmocr.utils.ocr.Config.fromfile')
('mmocr.utils.ocr.load_checkpoint')
('mmocr.utils.ocr.model_inference')
def test_single_inference(mock_model_inference, mock_loading, mock_config, mock_build_detector, mock_init_detector):
def dummy_inference(mo... |
def _recall_update(input: torch.Tensor, target: torch.Tensor, num_classes: Optional[int], average: Optional[str]) -> Tuple[(torch.Tensor, torch.Tensor, torch.Tensor)]:
_recall_update_input_check(input, target, num_classes)
if (input.ndim == 2):
input = torch.argmax(input, dim=1)
if (average == 'micr... |
class ParallelReadConcat(IterDataPipe):
def __init__(self, *datapipes: IterDataPipe, dp_selector: Callable[([Sequence[IterDataPipe]], Sequence[IterDataPipe])]=_default_dp_selector) -> None:
super().__init__()
self.datapipes: Tuple[(IterDataPipe, ...)] = datapipes
self.dp_selector = dp_select... |
def test_show_dynamic(hatch, temp_dir):
project_name = 'My.App'
with temp_dir.as_cwd():
hatch('new', project_name)
path = (temp_dir / 'my-app')
with path.as_cwd():
result = hatch('version')
assert (result.exit_code == 0), result.output
assert (result.output == '0.0.1\n') |
('torch.__version__', torch_version)
.parametrize('in_w,in_h,in_feature,out_feature', [(10, 10, 1, 1), (20, 20, 3, 3)])
def test_linear(in_w, in_h, in_feature, out_feature):
x_empty = torch.randn(0, in_feature, requires_grad=True)
torch.manual_seed(0)
wrapper = Linear(in_feature, out_feature)
wrapper_ou... |
def main(argv):
(parser, subparsers) = setup_args()
for c in codecs:
cparser = subparsers.add_parser(c.__name__.lower(), help=f'{c.__name__}')
setup_common_args(cparser)
c.setup_args(cparser)
args = parser.parse_args(argv)
codec_cls = next((c for c in codecs if (c.__name__.lower(... |
_torch
_vision
class EfficientFormerModelIntegrationTest(unittest.TestCase):
_property
def default_feature_extractor(self):
return (EfficientFormerImageProcessor.from_pretrained('snap-research/efficientformer-l1-300') if is_vision_available() else None)
def test_inference_image_classification_head(s... |
def parse_handshake(handshake):
reader = StreamReader()
reader.feed_data(handshake)
parser = Request.parse(reader.read_line)
try:
next(parser)
except StopIteration:
pass
else:
assert False, 'parser should return request'
reader.feed_eof()
assert reader.at_eof(), '... |
.parametrize('dm', [partial(qutip.thermal_dm, n=1.0), qutip.maximally_mixed_dm, partial(qutip.coherent_dm, alpha=0.5), partial(qutip.fock_dm, n=1), partial(qutip.spin_state, m=2, type='dm'), partial(qutip.spin_coherent, theta=1, phi=2, type='dm')], ids=['thermal_dm', 'maximally_mixed_dm', 'coherent_dm', 'fock_dm', 'spi... |
def test_js_quirks_match_files(webengine_tab):
quirks_path = ((pathlib.Path(qutebrowser.__file__).parent / 'javascript') / 'quirks')
suffix = '.user.js'
quirks_files = {p.name[:(- len(suffix))] for p in quirks_path.glob(f'*{suffix}')}
quirks_code = {q.filename for q in webengine_tab._scripts._get_quirks... |
class EmailTest(object):
def assert_bad_email(self, validator, value, msg=None):
msg = (msg or '{0} is not a valid email')
with pytest.raises(ValueError) as cm:
validator(value)
assert (str(cm.value) == msg.format(value))
.parametrize('value', ['', '', 'coucou+', '', '-with-h... |
def _get_sequence(exons, genome, strand='+'):
seq = []
pos = []
for exon in exons:
seq.append(genome[exon[0]:exon[1]])
pos.extend(range(exon[0], exon[1]))
if (strand == '-'):
return (rev_complement(''.join(seq)), pos)
else:
return (''.join(seq), pos) |
class RegNetParams():
def __init__(self, depth: int, w_0: int, w_a: float, w_m: float, group_w: int, stem_type: StemType='SIMPLE_STEM_IN', stem_width: int=32, block_type: BlockType='RES_BOTTLENECK_BLOCK', activation_type: ActivationType='RELU', use_se: bool=True, se_ratio: float=0.25, bn_epsilon: float=1e-05, bn_mo... |
_rewriter([BetaBinomialRV])
def beta_binomial_from_beta_binomial(fgraph, node):
(rng, *other_inputs, n, a, b) = node.inputs
(n, a, b) = broadcast_arrays(n, a, b)
(next_rng, b) = beta.make_node(rng, *other_inputs, a, b).outputs
(next_rng, b) = binomial.make_node(next_rng, *other_inputs, n, b).outputs
... |
('pyinaturalist.auth._get_jwt', return_value=NOT_CACHED_RESPONSE)
def test_get_access_token__invalid_creds(mock_get_jwt, requests_mock):
requests_mock.post(f'{API_V0}/oauth/token', json=token_rejected_json, status_code=401)
with pytest.raises(HTTPError):
get_access_token('username', 'password', 'app_id'... |
class Translations(NullTranslations, gettext.GNUTranslations):
DEFAULT_DOMAIN = 'messages'
def __init__(self, fp: (gettext._TranslationsReader | None)=None, domain: (str | None)=None):
super().__init__(fp=fp)
self.domain = (domain or self.DEFAULT_DOMAIN)
ugettext = gettext.GNUTranslations.ge... |
class LoginActionTest(BaseActionTest):
def test_login(self):
self.do_login()
def test_login_with_partial_pipeline(self):
self.do_login_with_partial_pipeline()
def test_fields_stored_in_session(self):
self.strategy.set_settings({'SOCIAL_AUTH_FIELDS_STORED_IN_SESSION': ['foo', 'bar']})... |
.parametrize('value', [np.nan, np.inf])
.filterwarnings('ignore:Cannot cache compiled function "numba_funcified_fgraph"')
def test_solve_triangular_raises_on_nan_inf(value):
A = pt.matrix('A')
b = pt.matrix('b')
X = pt.linalg.solve_triangular(A, b, check_finite=True)
f = pytensor.function([A, b], X, mod... |
class TestTrainingExtensionsWeightSvdCostCalculator(unittest.TestCase):
def test_calculate_weight_svd_cost(self):
conv = nn.Conv2d(32, 64, kernel_size=5, padding=(2, 2))
layer = Layer(conv, 'conv', output_shape=[1, 64, 28, 28])
self.assertEqual(32, cc.WeightSvdCostCalculator.calculate_max_ra... |
def add_arguments(parser):
parser.description = 'Python Language Server'
parser.add_argument('--tcp', action='store_true', help='Use TCP server instead of stdio')
parser.add_argument('--ws', action='store_true', help='Use Web Sockets server instead of stdio')
parser.add_argument('--host', default='127.0... |
def _makeTags(tagStr, xml, suppress_LT=Suppress('<'), suppress_GT=Suppress('>')):
if isinstance(tagStr, str_type):
resname = tagStr
tagStr = Keyword(tagStr, caseless=(not xml))
else:
resname = tagStr.name
tagAttrName = Word(alphas, (alphanums + '_-:'))
if xml:
tagAttrValu... |
class Solution(object):
def networkDelayTime(self, times, N, K):
graph = collections.defaultdict(list)
for (u, v, w) in times:
graph[u].append((v, w))
dist = {node: float('inf') for node in xrange(1, (N + 1))}
seen = ([False] * (N + 1))
dist[K] = 0
while T... |
def resolve_dns_srv(host: str):
srv_records = dns.resolver.query(host, 'SRV')
srv_records = sorted(srv_records, key=(lambda x: (x.priority, (- x.weight))))
def dict_from_srv_record(srv):
return {'host': str(srv.target), 'port': srv.port}
return [dict_from_srv_record(srv) for srv in srv_records] |
def test_private_is_deprecated() -> None:
class PrivateInit():
def __init__(self, foo: int, *, _ispytest: bool=False) -> None:
deprecated.check_ispytest(_ispytest)
with pytest.warns(pytest.PytestDeprecationWarning, match='private pytest class or function'):
PrivateInit(10)
Privat... |
class PyObjectToTextual():
def __init__(self, project):
self.project = project
def transform(self, pyobject):
if (pyobject is None):
return ('none',)
object_type = type(pyobject)
try:
method = getattr(self, (object_type.__name__ + '_to_textual'))
... |
class TrainerMemoryTracker():
stages = {'__init__': 'init', 'train': 'train', '_inner_training_loop': 'train', 'evaluate': 'eval', 'predict': 'test'}
def __init__(self, skip_memory_metrics=False):
self.skip_memory_metrics = skip_memory_metrics
if (not is_psutil_available()):
self.ski... |
('rendered_page_break.preceding_paragraph_fragment is the content before break')
def then_rendered_page_break_preceding_paragraph_fragment_is_the_content_before_break(context: Context):
para_frag = context.rendered_page_break.preceding_paragraph_fragment
actual_value = type(para_frag).__name__
expected_valu... |
def test_typeshed(args: TestConfig, tempdir: Path) -> TestSummary:
print(f'*** Testing Python {args.version} on {args.platform}')
(stdlib_dir, stubs_dir) = (Path('stdlib'), Path('stubs'))
summary = TestSummary()
if ((stdlib_dir in args.filter) or any(((stdlib_dir in path.parents) for path in args.filter... |
def test_path_warning(pipx_temp_env, capsys, monkeypatch, caplog):
assert (not run_pipx_cli(['install', 'pycowsay']))
assert ('is not on your PATH environment variable' not in unwrap_log_text(caplog.text))
monkeypatch.setenv('PATH', '')
assert (not run_pipx_cli(['install', 'pycowsay', '--force']))
a... |
def call_api(input_json: Dict[(str, Any)], api_key) -> Dict[(str, Any)]:
headers = {'X-API-Key': api_key, 'Content-Type': 'application/json'}
url = '
response = requests.post(url, headers=headers)
if (response.status_code == 200):
return response.json()
else:
return {'status_code': r... |
def valid_int(s, min_value=None, max_value=None):
if (s is None):
return (False, 'cannot is None')
if (not isinstance(s, str)):
return (False, 'must a string value')
s = int(s)
if ((max_value is not None) and (s > max_value)):
return (False, ('%d must less than %d' % (s, max_valu... |
def get_module_inp_acts(module: torch.nn.Module, model: torch.nn.Module, params: SeqMseParams, forward_fn: Callable, cached_dataset: CachedDataset) -> torch.Tensor:
inp_acts = []
def hook_fn(_, inp, __):
if isinstance(inp, tuple):
inp_acts.append(inp[0])
raise StopForwardException
... |
def init_state(model, state_in, state_out, dt):
wp.launch(kernel=integrate_particles, dim=model.particle_count, inputs=[state_in.particle_q, state_in.particle_qd, state_in.particle_f, model.particle_inv_mass, model.gravity, dt], outputs=[state_out.particle_q, state_out.particle_qd], device=model.device) |
def factor(n):
isqrt = getattr(math, 'isqrt', (lambda x: int(math.sqrt(x))))
for prime in sieve((isqrt(n) + 1)):
while True:
(quotient, remainder) = divmod(n, prime)
if remainder:
break
(yield prime)
n = quotient
if (n == 1):
... |
_SAMPLERS.register_module()
class CustomGroupMultiSourceSampler(GroupMultiSourceSampler):
def _get_source_group_info(self) -> None:
num_sources = len(self.num_per_source)
self.group2size_per_source = [{0: 0, 1: 0} for _ in range(num_sources)]
self.group2inds_per_source = [{0: [], 1: []} for ... |
def try_accept_invite(code, user):
(team, inviter) = model.team.confirm_team_invite(code, user)
model.notification.delete_matching_notifications(user, 'org_team_invite', org=team.organization.username)
orgname = team.organization.username
log_action('org_team_member_invite_accepted', orgname, {'member':... |
def test_wandb_hook():
sys.modules['wandb'] = MagicMock()
runner = _build_demo_runner()
hook = WandbLoggerHook()
loader = DataLoader(torch.ones((5, 2)))
runner.register_hook(hook)
runner.run([loader, loader], [('train', 1), ('val', 1)])
shutil.rmtree(runner.work_dir)
hook.wandb.init.asse... |
_REGISTRY.register()
class VideoTestDUFDataset(VideoTestDataset):
def __getitem__(self, index):
folder = self.data_info['folder'][index]
(idx, max_idx) = self.data_info['idx'][index].split('/')
(idx, max_idx) = (int(idx), int(max_idx))
border = self.data_info['border'][index]
... |
class GenericRemote(RemoteControl):
def __init__(self, tvFactory: TVFactory):
super().__init__(tvFactory)
def nextChannel(self) -> None:
channel: int = self.getChannel()
self.setChannel((channel + 1))
def prevChannel(self) -> None:
channel: int = self.getChannel()
sel... |
class Counter():
def __init__(self, transport: Transport, name: bytes, tags: Optional[Dict[(str, Any)]]=None):
self.transport = transport
self.name = name
self.tags = tags
def increment(self, delta: float=1.0, sample_rate: float=1.0) -> None:
self.send(delta, sample_rate)
def... |
def find_lib(elf: ELFFile, lib: str, ldpaths: list[str], root: str='/') -> tuple[((str | None), (str | None))]:
for ldpath in ldpaths:
path = os.path.join(ldpath, lib)
target = readlink(path, root, prefixed=True)
if os.path.exists(target):
with open(target, 'rb') as f:
... |
def postprocess_text(preds, responses, metric_name):
_preds = [pred.strip() for pred in preds]
_responses = [response.strip() for response in responses]
if (metric_name == 'rouge'):
_preds = ['\n'.join(nltk.sent_tokenize(pred)) for pred in _preds]
_responses = ['\n'.join(nltk.sent_tokenize(r... |
.supported(only_if=(lambda backend: backend.hash_supported(hashes.SHA512_224())), skip_message='Does not support SHA512/224')
class TestSHA512224():
test_sha512_224 = generate_hash_test(load_hash_vectors, os.path.join('hashes', 'SHA2'), ['SHA512_224LongMsg.rsp', 'SHA512_224ShortMsg.rsp'], hashes.SHA512_224()) |
.usefixtures('hook_fixture')
def test_hook_calls_subscriber_async_in_existing_loop():
async def t():
val = 0
async def co(new_val):
nonlocal val
val = new_val
hook.subscribe.group_window_add(co(8))
hook.fire('group_window_add')
(await asyncio.sleep(0))... |
class Plugins():
steps_by_id: Dict[(str, PluginStep)]
def __init__(self, steps: List[PluginStep]):
self.steps_by_id = dict()
for step in steps:
if (step.schema.id in self.steps_by_id):
raise Exception('Duplicate step ID: {}'.format(step.schema.id))
self.st... |
class Encoder(nn.Module):
def __init__(self, encoder, quant_conv, quantize):
super().__init__()
self.encoder = encoder
self.quant_conv = quant_conv
self.quantize = quantize
_grad()
def forward(self, x):
x = ((2 * x) - 1)
h = self.encoder(x)
h = self.qu... |
class YahooOAuth2(BaseOAuth2):
name = 'yahoo-oauth2'
ID_KEY = 'sub'
AUTHORIZATION_URL = '
ACCESS_TOKEN_URL = '
ACCESS_TOKEN_METHOD = 'POST'
EXTRA_DATA = [('sub', 'id'), ('access_token', 'access_token'), ('expires_in', 'expires'), ('refresh_token', 'refresh_token'), ('token_type', 'token_type')]
... |
class ModuleType(Enum):
AVAILABLE = 1
RESERVED = 2
BLOCKED = 3
def to_char(module):
if (module == ModuleType.AVAILABLE):
return '1'
elif (module == ModuleType.RESERVED):
return '2'
elif (module == ModuleType.BLOCKED):
return '0'
def to_colo... |
def parse(code: str, module_name: str='', path: (str | None)=None, apply_transforms: bool=True) -> nodes.Module:
code = textwrap.dedent(code)
builder = AstroidBuilder(manager=AstroidManager(), apply_transforms=apply_transforms)
return builder.string_build(code, modname=module_name, path=path) |
class AdversarialAttacker():
def __init__(self):
self.phonetic_attacker = PhoneticAttacker(stats_folder=os.path.join(os.path.realpath(os.path.dirname(__file__)), 'phonetic_attacks/statistics'))
self.confusable_attacker = UnicodeConfusable()
self.methods = ['phonetic', 'full-swap', 'inner-swa... |
def for_each_class():
for kobj in kset_for_each_object(gdb.parse_and_eval('class_kset')):
subsys = container_of(kobj, kset_type.get_type().pointer(), 'kobj')
subsys_priv = container_of(subsys, subsys_private_type.get_type().pointer(), 'subsys')
(yield subsys_priv['class']) |
def note_detection_with_onset_offset_regress(frame_output, onset_output, onset_shift_output, offset_output, offset_shift_output, velocity_output, frame_threshold):
output_tuples = []
bgn = None
frame_disappear = None
offset_occur = None
for i in range(onset_output.shape[0]):
if (onset_output... |
_fixtures(WebFixture, PartyAccountFixture, InputScenarios)
def test_persisting_input(web_fixture, party_account_fixture, input_scenarios):
(Form)
class FormStub():
view = web_fixture.view
user_interface = EmptyStub(name='myui')
channel_name = 'myform'
fixture = input_scenarios
fo... |
class HerokuTests(unittest.TestCase):
def setUp(self):
self.server = heroku.Host()
def test_port(self):
old_port = os.environ.get('PORT')
def reset_port():
if (old_port is None):
del os.environ['PORT']
else:
os.environ['PORT'] = old... |
def run(client: Client, args: Namespace, config: Config):
wait_for_cluster(client, shutdown_on_failure=True)
assert (len(client.scheduler_info()['workers']) > 0)
setup_memory_pools(client, (args.type == 'gpu'), args.rmm_pool_size, args.disable_rmm_pool, args.enable_rmm_async, args.enable_rmm_managed, args.r... |
.parametrize('username,password,email', site_managers)
def test_is_site_manager_returns_true_for_site_managers(db, client, username, password, email):
client.login(username=username, password=password)
user = get_user_model().objects.get(username=username, email=email)
assert (is_site_manager(user) is True) |
def test_AddValueToZero_simple_weights_gt0():
dm = skcriteria.mkdm(matrix=[[1, 2, 3], [4, 5, 6]], objectives=[min, max, min], weights=[1, 2, 3])
expected = skcriteria.mkdm(matrix=[[1, 2, 3], [4, 5, 6]], objectives=[min, max, min], weights=[1, 2, 3])
scaler = AddValueToZero(value=0.5, target='weights')
r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.