code stringlengths 281 23.7M |
|---|
class CosFaceLoss(LargeMarginSoftmaxLoss):
def __init__(self, *args, margin=0.35, scale=64, **kwargs):
super().__init__(*args, margin=margin, scale=scale, **kwargs)
def init_margin(self):
pass
def cast_types(self, dtype, device):
self.W.data = c_f.to_device(self.W.data, device=device... |
def test_using_last_explicit_seed(ourtester):
ourtester.makepyfile(test_one='\n def test_a():\n pass\n ')
out = ourtester.runpytest('--randomly-seed=33')
out.assert_outcomes(passed=1, failed=0)
out.stdout.fnmatch_lines(['Using --randomly-seed=33'])
out = ourtester.runpytest(... |
def model(pretrained=False, **kwargs):
model = VGG(make_layers(cfg['O'], dilation=dilation['D1']), **kwargs)
if pretrained:
model_dict = model.state_dict()
pretrained_dict = model_zoo.load_url(model_urls['vgg16'])
print('load pretrained model from {}'.format(model_urls['vgg16']))
... |
class CheckpointHandler():
def __init__(self, coordinator_args: CoordinatorArguments, collab_optimizer_args: CollaborativeOptimizerArguments, averager_args: AveragerArguments, dht: hivemind.DHT):
self.save_checkpoint_step_interval = coordinator_args.save_checkpoint_step_interval
self.repo_path = coo... |
def test_async_event_hook():
calls = []
()
def handler1(*args):
assert_gt(len(args), 0)
calls.append(('handler1%s' % str(args)))
def handler2(*args):
calls.append(('handler2%s' % str(args)))
hook = AsyncEventHook([handler1])
hook.subscribe(handler2)
hook.trigger(1, 2,... |
def main(args):
print(args)
if args.database:
databases_to_fix = [args.database]
else:
databases_to_fix = set((list(implemented_database_fixes.keys()) + list(databases_add_foreign_keys.keys())))
for db in databases_to_fix:
if ((db not in implemented_database_fixes) and (db not in... |
def test_separate_processes():
test_args = ('python', 'tests/standalone_script.py')
run_params = {'args': test_args, 'capture_output': True, 'text': True}
run_process = functools.partial(subprocess.run, **run_params)
result = run_process()
assert (result.stdout.strip() == 'two 2')
start = time()... |
_tf
class TFXGLMModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = ((TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ())
all_generative_model_classes = ((TFXGLMForCausalLM,) if is_tf_available() else ())
pipeline_model_mapping = ({'feature-extraction': TFXGL... |
()
('-n', '--nodeid', default=None)
('-a', '--allof', default=None)
('-o', '--offset', default='')
_options
_options
def submit(nodeid, allof, offset, metadir, accept_metadir, controller, ctrlopt, modelsetup, modelopt, backend, local, verbosity):
handle_common_options(verbosity)
ys = handle_connection_options(m... |
_fixtures(ConfigWithFiles)
def test_incorrect_settings(config_with_files):
fixture = config_with_files
config_file = fixture.new_config_file(filename=ConfigWithSetting.filename, contents='some_key.some_wrong_name = 3')
fixture.set_config_spec(easter_egg, 'reahl.component_dev.test_config:ConfigWithSetting')
... |
class InceptionV1Test(tf.test.TestCase):
def testBuildClassificationNetwork(self):
batch_size = 5
(height, width) = (224, 224)
num_classes = 1000
inputs = tf.random_uniform((batch_size, height, width, 3))
(logits, end_points) = inception.inception_v1(inputs, num_classes)
... |
.integration
def test_arms_import(long_project):
new_arms = [{'arm_num': 3, 'name': 'Drug C'}]
response = long_project.import_arms(new_arms)
assert (response == 1)
new_events = [{'event_name': 'new_event', 'arm_num': '3'}]
response = long_project.import_events(new_events)
response = long_project... |
def main():
args = get_args()
if args.dir:
args.dirs = [item for sublist in args.dir for item in sublist]
else:
args.dirs = []
symbolizer = Symbolizer(sys.stdout, args.dirs, args.strip_path)
for line in sys.stdin:
symbolizer.write(line)
symbolizer.flush() |
class SilentListener(AbstractListener):
def _set_volume(self, volume):
pass
def _set_position(self, position):
pass
def _set_forward_orientation(self, orientation):
pass
def _set_up_orientation(self, orientation):
pass
def _set_orientation(self):
pass |
def test_parse_tree():
problem = '(q-transform/hint (quote (lambda (cdr (cdr (var ()))))) (quote ((() y . 1) (#f y () . #t) (#f b () b . y) (x #f (#f . #f) . #t) (a #f y x s . a))))'
step = 0
print('Starting problem:', problem)
with Interaction(lisp.parse(problem)) as env:
signal = None
... |
def tsym_block(qubits: List[cirq.Qid], params: List[Number]) -> List[cirq.Operation]:
mapped_circuit = _load_circuit('tsym_permute.json').transform_qubits({cirq.GridQubit(0, 0): qubits[0], cirq.GridQubit(0, 1): qubits[1]})
rots = [(cirq.Y(qubits[0]) ** params[0]), (cirq.Y(qubits[1]) ** params[1])]
return (r... |
class CLinker(Linker):
def __init__(self, schedule=None):
self.fgraph = None
super().__init__(scheduler=schedule)
def accept(self, fgraph: 'FunctionGraph', no_recycling=None, profile=None) -> 'CLinker':
if (no_recycling is None):
no_recycling = []
if ((self.fgraph is ... |
class Effect6669(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.drones.filteredItemBoost((lambda mod: mod.item.requiresSkill('Drones')), 'armorHP', src.getModifiedItemAttr('hullHpBonus'), **kwargs)
fit.drones.filteredItemBoost((lambda mod: mod.item.r... |
class DeleteEdges(StateChanger):
def __init__(self, from_node: NodeEnumerator, relations, to_node: NodeEnumerator, delete_reverse=False):
self.from_node = from_node
self.relations = relations
self.to_node = to_node
self.delete_reverse = delete_reverse
def apply_changes(self, stat... |
def test__calc_stats(detect_clearsky_helper_data):
(x, samples_per_window, sample_interval, H) = detect_clearsky_helper_data
mean_x = pd.Series((np.array([np.nan, np.nan, 5, 14, 29, 50, 77]) / 3.0))
max_x = pd.Series(np.array([np.nan, np.nan, 4, 9, 16, 25, 36]))
diff_std = np.array([np.nan, np.nan, np.s... |
class TestClientTransactions(KazooTestCase):
def setUp(self):
KazooTestCase.setUp(self)
skip = False
if (CI_ZK_VERSION and (CI_ZK_VERSION < (3, 4))):
skip = True
elif (CI_ZK_VERSION and (CI_ZK_VERSION >= (3, 4))):
skip = False
else:
ver = s... |
def list_deltas(namespace: str, table_name: str, partition_values: Optional[List[Any]]=None, table_version: Optional[str]=None, first_stream_position: Optional[int]=None, last_stream_position: Optional[int]=None, ascending_order: Optional[bool]=None, include_manifest: bool=False, *args, **kwargs) -> ListResult[Delta]:
... |
_oriented
class DenseTSDF(BaseMap):
def __init__(self, map_scale=[10, 10], voxel_scale=0.05, texture_enabled=False, max_disp_particles=(1024 * 1024), num_voxel_per_blk_axis=16, max_ray_length=10, min_ray_length=0.3, internal_voxels=10, max_submap_num=1024, is_global_map=False, disp_ceiling=1.8, disp_floor=(- 0.3), ... |
class CheckDummiesTester(unittest.TestCase):
def test_clean_code(self):
self.assertEqual(clean_code('"""\nDocstring\n"""\ncode\n"""Long string"""\ncode\n'), 'code\ncode')
self.assertEqual(clean_code("'''\nDocstring\n'''\ncode\n'''Long string'''\ncode\n'''"), 'code\ncode')
self.assertEqual(cl... |
.parametrize('found_file', ['build/pdf.js', 'build/pdf.mjs'])
def test_get_pdfjs_js_path(found_file: str, monkeypatch: pytest.MonkeyPatch):
def fake_pdfjs_res(requested):
if requested.endswith(found_file):
return
raise pdfjs.PDFJSNotFound(requested)
monkeypatch.setattr(pdfjs, 'get_pd... |
class UniformSuperpostionIJFirstQuantization(Bloq):
eta: int
num_bits_rot_aa: int
adjoint: int = False
_property
def signature(self) -> Signature:
n_eta = (self.eta - 1).bit_length()
return Signature.build(i=n_eta, j=n_eta)
def build_call_graph(self, ssa: 'SympySymbolAllocator') ... |
class VGG(nn.Module):
def __init__(self, features, num_classes=10, init_weights=True):
super(VGG, self).__init__()
self.features = features
self.avgpool = nn.AdaptiveAvgPool2d((7, 7))
self.classifier = nn.Sequential(nn.Linear(((512 * 7) * 7), 4096), nn.ReLU(True), nn.Dropout(), nn.Li... |
class DummySparseLabelOp(SparseLabelOp):
def register_length(self) -> (int | None):
return None
def _new_instance(self, data: Mapping[(str, complex)], *, other: (SparseLabelOp | None)=None) -> SparseLabelOp:
return self.__class__(data, copy=False)
def _validate_keys(self, keys: Collection[st... |
def _conv2d_wrapper(x, w, stride=1, padding=0, groups=1, transpose=False, flip_weight=True):
(_out_channels, _in_channels_per_group, kh, kw) = _get_weight_shape(w)
if ((not flip_weight) and ((kw > 1) or (kh > 1))):
w = w.flip([2, 3])
op = (conv2d_gradfix.conv_transpose2d if transpose else conv2d_gra... |
class TestExtensions():
def test_no_extensions(self, backend):
cert = _load_cert(os.path.join('x509', 'verisign_md2_root.pem'), x509.load_pem_x509_certificate)
ext = cert.extensions
assert (len(ext) == 0)
assert (list(ext) == [])
with pytest.raises(x509.ExtensionNotFound) as ... |
def batch_by_size(indices, num_tokens_fn, max_tokens=None, max_sentences=None, required_batch_size_multiple=1, distributed=False):
max_tokens = (max_tokens if (max_tokens is not None) else sys.maxsize)
max_sentences = (max_sentences if (max_sentences is not None) else sys.maxsize)
bsz_mult = required_batch_... |
class ScientificInput(Input, QtWidgets.QDoubleSpinBox):
def __init__(self, parameter, parent=None, **kwargs):
super().__init__(parameter=parameter, parent=parent, **kwargs)
if parameter.step:
self.setButtonSymbols(QtWidgets.QAbstractSpinBox.ButtonSymbols.UpDownArrows)
self.se... |
class LOGSSIM(torch.nn.Module):
def __init__(self, window_size=11, size_average=True):
super(LOGSSIM, self).__init__()
self.window_size = window_size
self.size_average = size_average
self.channel = 1
self.window = create_window(window_size, self.channel)
def forward(self,... |
def evaluate(best_sum_loss, best_final_loss, best_flag, lr):
print('\n > evalute the model')
STEPS = 100
x = np.arange(STEPS)
Adam = 'Adam'
LSTM_learner = Learner(f, LSTM_optimizer, STEPS, eval_flag=True, reset_theta=True, retain_graph_flag=True)
SGD_Learner = Learner(f, SGD, STEPS, eval_flag=Tr... |
def cifar10_testdata(batch_size):
transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.201))])
testset = torchvision.datasets.CIFAR10(root='../cifar10', train=False, download=True, transform=transform_test)
testloader = torch.utils.dat... |
class TestGetTableCommentFromExplain(unittest.TestCase):
def setUpClass(cls):
cls.spark = SparkSession.builder.getOrCreate()
cls.llm_mock = MagicMock(spec=BaseLanguageModel)
cls.spark_ai = SparkAI(llm=cls.llm_mock, spark_session=cls.spark)
def tearDownClass(cls):
cls.spark.stop()... |
def cleanup():
global __debug_file_handle
global gdb_process
global gdb_threads
for t in gdb_threads:
t.join(get_setting('gdb_timeout', 20))
gdb_threads = []
gdb_process = None
if get_setting('close_views', True):
for view in gdb_views:
view.close()
if get_set... |
class _PSPHead(nn.Module):
def __init__(self, in_channels, nclass, norm_layer=nn.BatchNorm2d, norm_kwargs=None, **kwargs):
super(_PSPHead, self).__init__()
self.psp = _PyramidPooling(in_channels, norm_layer=norm_layer, norm_kwargs=norm_kwargs)
if (in_channels == 512):
out_channel... |
class Params(object):
def __init__(self, **kwargs):
self.shift_scale = 6.0
self.min_shift = 0.5
self.shift_distribution = ShiftDistribution.UNIFORM
self.deformator_lr = 0.0001
self.shift_predictor_lr = 0.0001
self.n_steps = int(100000.0)
self.batch_size = 32
... |
class GroupLDAPGroupLink(RESTObject):
_repr_attr = 'provider'
def _get_link_attrs(self) -> Dict[(str, str)]:
data = {'provider': self.provider}
if self.cn:
data['cn'] = self.cn
else:
data['filter'] = self.filter
return data
def delete(self, **kwargs: A... |
class ModulatedDeformConv2d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation=1, groups=1, deformable_groups=1, im2col_step=64, bias=True):
super(ModulatedDeformConv2d, self).__init__()
if ((in_channels % groups) != 0):
raise ValueError('in_... |
class Messages(DeleteMessages, EditMessageCaption, EditMessageReplyMarkup, EditMessageMedia, EditMessageText, ForwardMessages, GetMediaGroup, GetMessages, SendAudio, SendChatAction, SendContact, SendDocument, SendAnimation, SendLocation, SendMediaGroup, SendMessage, SendPhoto, SendSticker, SendVenue, SendVideo, SendVid... |
(cls=ColoredCommand)
def markers(**raw_config: Any) -> NoReturn:
raw_config['command'] = 'markers'
pm = storage.get()
try:
config = pm.hook.pytask_configure(pm=pm, raw_config=raw_config)
session = Session.from_config(config)
except (ConfigurationError, Exception):
console.print_e... |
def replace_vars(a, table):
if (is_ast(a) and (not is_literal(a))):
if (type(a) == name_e):
if (a.id in table):
return table[a.id]
else:
return a
if (type(a) == call_e):
return call_e(a.func, *[replace_vars(x, table) for x in a[1:]]... |
def test_add_permissions(tmpfolder):
_ = tmpfolder
with temp_umask(219):
path = uniqpath()
create(path, 'contents', {})
assert (stat.S_IMODE(path.stat().st_mode) == 292)
path = uniqpath()
if (os.name == 'posix'):
add_permissions(stat.S_IXOTH)(path, 'contents',... |
class DonutImageProcessingTester(unittest.TestCase):
def __init__(self, parent, batch_size=7, num_channels=3, image_size=18, min_resolution=30, max_resolution=400, do_resize=True, size=None, do_thumbnail=True, do_align_axis=False, do_pad=True, do_normalize=True, image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5]... |
(RandomStateNumbaType)
def box_random_state(typ, val, c):
(pos, state_list) = _helperlib.rnd_get_state(_helperlib.rnd_get_np_state_ptr())
rng = RandomState()
rng.set_state(('MT19937', state_list, pos))
class_obj = c.pyapi.unserialize(c.pyapi.serialize_object(rng))
return class_obj |
((torch.cuda.device_count() < 2), 'test requires 2 GPUs')
class TestBMUF(unittest.TestCase):
def bmuf_process(self, cfg, args, iterations):
processes = []
results = Manager().dict()
ctx = torch.multiprocessing.get_context('spawn')
for rank in range(args.distributed_world_size):
... |
class BalancedRemoteExpert(nn.Module):
def __init__(self, *, dht: DHT, uid_prefix: str, grid_size: Tuple[(int, ...)], forward_timeout: Optional[float]=None, backward_timeout: Optional[float]=None, update_period: float=30.0, backward_task_size_multiplier: float=2.5, **kwargs):
super().__init__()
if u... |
def inference(input_x, input_x_field, zeroWeights, oneDimWeights, thirdWeight):
secondValue = tf.reduce_sum(tf.multiply(oneDimWeights, input_x, name='secondValue'))
firstTwoValue = tf.add(zeroWeights, secondValue, name='firstTwoValue')
thirdValue = tf.Variable(0.0, dtype=tf.float32)
input_shape = input_... |
class _GettextCompiler(_Compiler):
compile_i = _Compiler.compile_n
compile_v = compile_zero
compile_w = compile_zero
compile_f = compile_zero
compile_t = compile_zero
def compile_relation(self, method, expr, range_list):
rv = []
expr = self.compile(expr)
for item in range... |
(inspect_parser)
def do_inspect(args: argparse.Namespace) -> None:
response = request(args.status_file, 'inspect', show=args.show, location=args.location, verbosity=args.verbose, limit=args.limit, include_span=args.include_span, include_kind=args.include_kind, include_object_attrs=args.include_object_attrs, union_a... |
def export_opml(user):
root = Element('opml', {'version': '1.0'})
head = SubElement(root, 'head')
title = SubElement(head, 'title')
title.text = '{0} subscriptions'.format(user.username)
body = SubElement(root, 'body')
for feed in user.feed_set.all():
item = SubElement(body, 'outline', {... |
class F19Handler(BaseHandler):
version = F19
commandMap = {'auth': commands.authconfig.FC3_Authconfig, 'authconfig': commands.authconfig.FC3_Authconfig, 'autopart': commands.autopart.F18_AutoPart, 'autostep': commands.autostep.FC3_AutoStep, 'bootloader': commands.bootloader.F19_Bootloader, 'btrfs': commands.btr... |
class VisibleLengthSetting(Object):
class __T(TBase):
def regularize_extra(self, val):
if isinstance(val, list):
return self._cls(key=val[0], value=val[1])
return val
def to_save(self, val):
return (val.key, val.value)
def to_save_xml(self,... |
_BOX_PREDICTOR.register('FPNPredictorNeighbor')
class FPNPredictorNeighbor(nn.Module):
def __init__(self, cfg):
super(FPNPredictorNeighbor, self).__init__()
num_classes = cfg.MODEL.ROI_BOX_HEAD.NUM_CLASSES
representation_size = cfg.MODEL.ROI_BOX_HEAD.NONLOCAL_OUT_CHANNELS
self.cls_sc... |
class ShardedQuantFeatureProcessedEmbeddingBagCollection(ShardedQuantEmbeddingBagCollection):
def __init__(self, module: EmbeddingBagCollectionInterface, table_name_to_parameter_sharding: Dict[(str, ParameterSharding)], env: ShardingEnv, fused_params: Optional[Dict[(str, Any)]]=None, device: Optional[torch.device]=... |
class PNGImageEncoder(ImageEncoder):
def get_file_extensions(self):
return ['.png']
def encode(self, image, filename, file):
image = image.get_image_data()
has_alpha = ('A' in image.format)
greyscale = (len(image.format) < 3)
if has_alpha:
if greyscale:
... |
class TritonGrammar(object):
def __init__(self, vars: List[Tuple[(Char, BitSize)]], ops: List[BvOp]):
self.ops = ops
self.vars_dict = {x[0]: x[1] for x in vars}
self.vars = list(self.vars_dict.keys())
self.size = self.vars_dict[self.vars[0]]
def non_terminal_operators(self) -> Li... |
class NIN(nn.Module):
def __init__(self, pooling):
super(NIN, self).__init__()
if (pooling == 'max'):
pool2d = nn.MaxPool2d((3, 3), (2, 2), (0, 0), ceil_mode=True)
elif (pooling == 'avg'):
pool2d = nn.AvgPool2d((3, 3), (2, 2), (0, 0), ceil_mode=True)
self.feat... |
def _bigint_from_bytes(bytes):
sizeof_int = 4
padding = (sizeof_int - (len(bytes) % sizeof_int))
bytes += (b'\x00' * padding)
int_count = int((len(bytes) / sizeof_int))
unpacked = struct.unpack('{}I'.format(int_count), bytes)
accum = 0
for (i, val) in enumerate(unpacked):
accum += ((... |
def stage_partition_from_file_paths(namespace: str, file_paths: List[str], *args, **kwargs) -> Partition:
ds.create_namespace(namespace, {}, **kwargs)
table_name = '-'.join(file_paths).replace('/', '_')
ds.create_table_version(namespace, table_name, '1', **kwargs)
stream = ds.get_stream(namespace, table... |
(persist=eval(os.getenv('PERSISTENT')))
def rank_matrices(matrix):
sorted_matrix = np.sort(matrix.flatten())[::(- 1)].reshape(matrix.shape)
rank = 1
ranked_matrix = np.zeros(matrix.shape)
pbar = tqdm.tqdm(total=int(((matrix.shape[0] ** 2) / 2)))
for i in range(matrix.shape[0]):
for j in rang... |
def view_area_command(sub_parsers):
parser: ArgumentParser = sub_parsers.add_parser('view-area', help='View information about an area.', formatter_class=argparse.MetavarTypeHelpFormatter)
parser.add_argument('--simplify', action='store_true', help='Simplify the RequirementSets')
parser.add_argument('region'... |
class FileListModel(QAbstractListModel):
numberPopulated = pyqtSignal(int)
def __init__(self, parent=None):
super(FileListModel, self).__init__(parent)
self.fileCount = 0
self.fileList = []
def rowCount(self, parent=QModelIndex()):
return self.fileCount
def data(self, ind... |
class resnet8x4_resnet8x4(nn.Module):
def __init__(self, num_classes):
super(resnet8x4_resnet8x4, self).__init__()
self.net1 = resnet8x4_aux(num_classes=num_classes)
self.net2 = resnet8x4_aux(num_classes=num_classes)
def forward(self, x, grad=True):
(logit1, ss_logits1) = self.ne... |
def properties(validator, properties, instance, schema):
if (not validator.is_type(instance, 'object')):
return
for (property, subschema) in properties.items():
if (property in instance):
(yield from validator.descend(instance[property], subschema, path=property, schema_path=property... |
def merge_encodings(default_encoding: Dict[(str, Dict[(str, Any)])], overrides: Dict[(str, Dict[(str, Any)])]) -> Dict[(str, Dict[(str, Any)])]:
merged = {}
for (var, d) in default_encoding.items():
if (var in overrides):
merged[var] = {**d, **overrides[var]}
else:
merged... |
class SentWebAppMessage(TelegramObject):
__slots__ = ('inline_message_id',)
def __init__(self, inline_message_id: Optional[str]=None, *, api_kwargs: Optional[JSONDict]=None):
super().__init__(api_kwargs=api_kwargs)
self.inline_message_id: Optional[str] = inline_message_id
self._id_attrs ... |
def train():
cmd = argparse.ArgumentParser(sys.argv[0], conflict_handler='resolve')
cmd.add_argument('--seed', default=1, type=int, help='The random seed.')
cmd.add_argument('--gpu', default=(- 1), type=int, help='Use id of gpu, -1 if cpu.')
cmd.add_argument('--train_path', required=True, help='The path... |
.parametrize('name,path,extras,constraint,expected', [('my-package', SAMPLE_PROJECT, None, None, f'my-package (*) {SAMPLE_PROJECT.as_uri()}'), ('my-package', SAMPLE_PROJECT, ['db'], '1.2', f'my-package[db] (1.2) {SAMPLE_PROJECT.as_uri()}')])
def test_directory_dependency_string_representation(name: str, path: Path, e... |
def cpu_count():
if (sys.platform == 'win32'):
try:
num = int(os.environ['NUMBER_OF_PROCESSORS'])
except (ValueError, KeyError):
num = 0
elif (('bsd' in sys.platform) or (sys.platform == 'darwin')):
comm = '/sbin/sysctl -n hw.ncpu'
if (sys.platform == 'dar... |
class ReLuBlurBlock(nn.Module):
def __init__(self, in_filters, temp=6.0, sfilter=(1, 1), pad_mode='constant', **kwargs):
super(ReLuBlurBlock, self).__init__()
self.temp = temp
self.blur = layers.blur(in_filters, sfilter=sfilter, pad_mode=pad_mode)
def forward(self, x):
x = torch.... |
class FindEntryServerTestCase(unittest.TestCase):
def setUp(self):
self.server = server.Server()
self.pocket = '0'
self.entry_id = self.server.run('add', name='Hiking boots', value=(- 111.11), pocket=self.pocket)['id']
def test_get_pocket(self):
pocket = self.server._get_pocket(s... |
_sample_fn.register(ptr.RandIntRV)
_sample_fn.register(ptr.IntegersRV)
_sample_fn.register(ptr.UniformRV)
def jax_sample_fn_uniform(op):
name = op.name
if isinstance(op, ptr.IntegersRV):
name = 'randint'
jax_op = getattr(jax.random, name)
def sample_fn(rng, size, dtype, *parameters):
rng... |
def get_tfds(train_file: str, eval_file: str, test_file: str, tokenizer: PreTrainedTokenizer, label_column_id: int, max_seq_length: Optional[int]=None):
files = {}
if (train_file is not None):
files[datasets.Split.TRAIN] = [train_file]
if (eval_file is not None):
files[datasets.Split.VALIDAT... |
class BaseOneDSpectrum(LowerDimensionalObject, MaskableArrayMixinClass, SpectralAxisMixinClass):
def __new__(cls, value, unit=None, dtype=None, copy=True, wcs=None, meta=None, mask=None, header=None, spectral_unit=None, fill_value=np.nan, wcs_tolerance=0.0):
if (np.asarray(value).ndim != 1):
rai... |
def test_hover_move_event_not_in_handles(view, item):
view.scene.addItem(item)
item.setSelected(True)
event = MagicMock()
event.pos.return_value = QtCore.QPointF(50, 50)
with patch.object(item, 'bounding_rect_unselected', return_value=QtCore.QRectF(0, 0, 1000, 800)):
item.hoverMoveEvent(even... |
def handle_options_and_args(_command, arguments, options):
for argument in arguments:
if isinstance(argument, dict):
_command = click.argument(list(argument.keys())[0], **handle_option_and_arg_data(list(argument.values())[0]))(_command)
else:
_command = click.argument(argumen... |
class ObjectiveFcn():
class Lagrange(FcnEnum):
CUSTOM = (PenaltyFunctionAbstract.Functions.custom,)
MINIMIZE_ANGULAR_MOMENTUM = (PenaltyFunctionAbstract.Functions.minimize_angular_momentum,)
MINIMIZE_COM_ACCELERATION = (PenaltyFunctionAbstract.Functions.minimize_com_acceleration,)
MI... |
.parametrize(['debugging_module', 'debugging_set_trace'], [('pdb', 'set_trace()'), pytest.param('ipdb', 'set_trace()', marks=pytest.mark.xfail(reason='waiting on to allow proper testing')), pytest.param('pydevd', 'settrace(port=4678)', marks=pytest.mark.xfail(reason='in need of way to setup pydevd server'))])
_spawn
d... |
def imagenet_iterator(cfg, kv):
val_rec = os.path.join(cfg.dataset.data_dir, 'val_256_q95.rec')
if (cfg.dataset.aug_level == 1):
train_rec = os.path.join(cfg.dataset.data_dir, 'train_256_q95.rec')
else:
train_rec = os.path.join(cfg.dataset.data_dir, 'train_480_q95.rec')
train = mx.io.Ima... |
def test_json_package_page() -> None:
s = SimpleAPI(Storage(), SimpleFormat.JSON, [], SimpleDigest.SHA256, False, None)
p = Package('69')
p._metadata = SIXTYNINE_METADATA
assert (EXPECTED_SIMPLE_SIXTYNINE_JSON_1_1 == s.generate_json_simple_page(p))
assert (EXPECTED_SIMPLE_SIXTYNINE_JSON_PRETTY_1_1 =... |
def test_config_file_errors_html(errors):
html = errors.to_html()
assert (textwrap.dedent(html) == textwrap.dedent('\n Errors occurred while reading config.py:\n\n <ul>\n\n <li>\n <b>Error text 1</b>: Exception 1\n\n </li>\n\n <li>\n <b>Er... |
def validate_(args, device_id, pt, step):
device = ('cpu' if (args.visible_gpus == '-1') else 'cuda')
if (pt != ''):
test_from = pt
else:
test_from = args.test_from
logger.info(('Loading checkpoint from %s' % test_from))
checkpoint = torch.load(test_from, map_location=(lambda storage... |
_default_category('Basic Completion')
class BasicCompletionCommandSet(CommandSet):
food_item_strs = ['Pizza', 'Ham', 'Ham Sandwich', 'Potato']
sport_item_strs = ['Bat', 'Basket', 'Basketball', 'Football', 'Space Ball']
file_strs = ['/home/user/file.db', '/home/user/file space.db', '/home/user/another.db', '... |
.django_db
def test_send_speaker_voucher_email(speaker_voucher_factory):
speaker_voucher = speaker_voucher_factory(voucher_code='ABC123', pretix_voucher_id=2)
with patch('domain_events.publisher.publish_message') as mock_publish:
send_speaker_voucher_email(speaker_voucher)
mock_publish.assert_called... |
class Stem(nn.Module):
def __init__(self, in_chs: int, out_chs: int, kernel_size: int=3, act_layer: str='gelu', norm_layer: str='batchnorm2d', norm_eps: float=1e-05):
super().__init__()
if (not isinstance(out_chs, (list, tuple))):
out_chs = to_2tuple(out_chs)
norm_act_layer = par... |
def sa_logp_target(target: float) -> GoalDirectedBenchmark:
specification = uniform_specification(1, 10, 100)
benchmark_object = logP_benchmark(target)
sa_biased = ScoringFunctionSAWrapper(benchmark_object.objective, SAScoreModifier())
return GoalDirectedBenchmark(name='SA_logP_target', objective=sa_bia... |
def _tempfile(reader, suffix='', *, _os_remove=os.remove):
(fd, raw_path) = tempfile.mkstemp(suffix=suffix)
try:
try:
os.write(fd, reader())
finally:
os.close(fd)
del reader
(yield pathlib.Path(raw_path))
finally:
try:
_os_remove(ra... |
def get_model(name, num_classes=10, stem=False, verbose=True, **block_kwargs):
if (name in ['alexnet_dnn', 'alexnet']):
model = alexnet.dnn(num_classes=num_classes, stem=stem, name=name, **block_kwargs)
elif (name in ['alexnet_mcdo']):
model = alexnet.mcdo(num_classes=num_classes, stem=stem, nam... |
def weekly_check_color_results(val):
failures = ['Unverified Treatment', 'Partial Treatment', 'Treatment Overridden', 'New Field Delivered', 'Prescription Altered', 'Site Setup Altered']
failure_flag = 0
for failure in failures:
if (failure in set(val)):
failure_flag += 1
else:
... |
class QuantizableBasicConv2d(BasicConv2d):
def __init__(self, *args, **kwargs):
super(QuantizableBasicConv2d, self).__init__(*args, **kwargs)
self.relu = nn.ReLU()
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.relu(x)
return x
def fuse_model(s... |
def pose_ren_net(net_type, iter_idx, output_dir, test_id=0):
dataset = 'msra'
n = caffe.NetSpec()
(fx_, fy_, ux_, uy_) = util.get_param(dataset)
point_num_ = util.get_joint_num(dataset)
root_folder_ = config.msra_data_dir
if (net_type == 'train'):
image_source_ = '{}/cache/train_image_{}... |
class Cnn14_DecisionLevelMax(nn.Module):
def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, fmax, classes_num, interpolate_mode='nearest'):
super(Cnn14_DecisionLevelMax, self).__init__()
window = 'hann'
center = True
pad_mode = 'reflect'
ref = 1.0
... |
def test_simple_opt_vectors_search():
fixture_records = generate_fixtures(skip_vectors=True)
searcher = TestSimpleSearcher()
local_client = init_local()
init_client(local_client, fixture_records)
remote_client = init_remote()
init_client(remote_client, fixture_records)
compare_client_results... |
.parametrize('test_args, expected', [(['0'], '0'), (['100'], '100'), (['-100'], '-100'), (['1000'], '1.0 thousand'), (['12400'], '12.4 thousand'), (['12490'], '12.5 thousand'), (['1000000'], '1.0 million'), (['-1000000'], '-1.0 million'), (['1200000'], '1.2 million'), (['1290000'], '1.3 million'), ([''], '1.0 billion')... |
def test_insert_items(view):
view.scene.update_selection = MagicMock()
view.scene.max_z = 5
item1 = BeePixmapItem(QtGui.QImage())
view.scene.addItem(item1)
item2 = BeePixmapItem(QtGui.QImage())
item2.setPos(50, 40)
command = commands.InsertItems(view.scene, [item2])
command.redo()
as... |
class Loss(pystiche.Module, ABC):
def __init__(self, *, encoder: Optional[enc.Encoder]=None, input_guide: Optional[torch.Tensor]=None, score_weight: float=1.0) -> None:
super().__init__()
self._encoder = encoder
self._input_guide: Optional[torch.Tensor]
self._input_enc_guide: Optiona... |
def parse_args():
parser = argparse.ArgumentParser(description='PyTorch Training', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--msg', default=False, type=distutils.util.strtobool, help='display message')
parser.add_argument('--resume', default='', type=str, metavar='PATH', ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.