code stringlengths 281 23.7M |
|---|
class TextualInversionCLIPTextModel(CLIPTextModel):
def __init__(self, config: CLIPTextConfig):
super().__init__(config)
(vocab_size, embed_dim) = self.text_model.embeddings.token_embedding.weight.size()
self.text_model.embeddings.token_embedding = SplitEmbedding(vocab_size, embed_dim)
d... |
def get_variants(args):
env_params = ENV_PARAMS[args.env]
params = COMMON_PARAMS
params.update(env_params)
vg = VariantGenerator()
for (key, val) in params.items():
if isinstance(val, list):
vg.add(key, val)
else:
vg.add(key, [val])
return vg |
class Migration(migrations.Migration):
dependencies = [('projects', '0044_meta')]
operations = [migrations.AddField(model_name='value', name='file', field=models.FileField(blank=True, help_text='The file stored for this value.', null=True, upload_to=rdmo.projects.models.value.get_file_upload_to, verbose_name='F... |
def _load_event_fixtures(fixture_dir):
fixtures = os.listdir(fixture_dir)
for filename in fixtures:
with open(os.path.join(fixture_dir, filename), 'r') as fp:
fixtures = yaml.load(fp.read())
for fixture in fixtures:
event = fixture.pop('event')
result = fixtur... |
def test_dataset_transform_override():
data1 = MemoryDataset({'x': [pic(1), pic(2), pic(3)], 'y': ['a', 'b', 'c']}, transform=Lambda((lambda x: (np.array(x)[(0, 0)] * 2))))
data2 = MemoryDataset({'x': [pic(4), pic(5), pic(6)], 'y': ['d', 'e', 'f']}, transform=Lambda((lambda x: (np.array(x)[(0, 0)] * 3))))
d... |
class CheckpointFunction(torch.autograd.Function):
def forward(ctx, run_function, parent_ctx_dict, kwarg_keys, *args):
if torch.is_grad_enabled():
checkpoint.check_backward_validity(args)
ctx.run_function = run_function
ctx.kwarg_keys = kwarg_keys
ctx.fwd_rng_state = util... |
def detect_slides_recursively(ctr_entities):
for ce in ctr_entities:
if isinstance(ce, (EBlock, EToGather, EToSatisfy)):
detect_slides_recursively(ce.entities)
elif (isinstance(ce, ESlide) and (len(ce.entities) == 1)):
son = ce.entities[0]
if (isinstance(son, EToG... |
def get_hessianloader(dataset, hessian_batch_size):
if (dataset == 'cifar10'):
hessian_loader = torch.utils.data.DataLoader(datasets.CIFAR10('../data/', train=True, download=True, transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.201))])),... |
def average_gradients(tower_grads):
average_grads = []
for grad_and_vars in zip(*tower_grads):
grads = []
for (g, _) in grad_and_vars:
expanded_g = tf.expand_dims(g, 0)
grads.append(expanded_g)
grad = tf.concat(grads, 0)
grad = tf.reduce_mean(grad, 0)
... |
class DisplayQueryUseCase():
def __init__(self, room_repo: RoomRDBRepository, db_session: Callable[([], ContextManager[Session])]):
self.room_repo = room_repo
self.db_session = db_session
def get_rooms(self, room_status: RoomStatus) -> List[Room]:
with self.db_session() as session:
... |
def load_partition_data_mnist_by_device_id(batch_size, device_id, train_path='MNIST_mobile', test_path='MNIST_mobile'):
train_path += ((('/' + device_id) + '/') + 'train')
test_path += ((('/' + device_id) + '/') + 'test')
return load_partition_data_mnist(batch_size, train_path, test_path) |
def _format_diff_text_and_options(diff, **kwargs):
valid_instructions = ('KEEP', 'REMOVE', 'ADD', 'UPDATE')
def _visualize(obj, rootname, get_name=False):
if utils.is_iter(obj):
if get_name:
return (obj[0] if obj[0] else '<unset>')
if (rootname == 'attrs'):
... |
class SeparableConv2d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, dilation=1, bias=False, BatchNorm=nn.BatchNorm2d):
super(SeparableConv2d, self).__init__()
if (dilation > (kernel_size // 2)):
padding = dilation
else:
padding = (... |
def auth_from_yaml(file_path, username=None, password=None):
auth_configs = yaml.load(open(file_path), Loader=yaml.FullLoader)
if ((username is None) or (password is None)):
auth_file = auth_configs.get('auth_file', False)
if (auth_file and os.path.isfile(auth_file)):
(username, pass... |
def test_it_should_remove_installed_packages_if_required() -> None:
transaction = Transaction([Package('a', '1.0.0'), Package('b', '2.0.0'), Package('c', '3.0.0')], [(Package('a', '1.0.0'), 1), (Package('b', '2.1.0'), 2), (Package('d', '4.0.0'), 0)], installed_packages=[Package('a', '1.0.0'), Package('b', '2.0.0'),... |
def get_tf_weights_as_numpy(path) -> Dict:
init_vars = tf.train.list_variables(path)
tf_weights = {}
ignore_name = ['global_step']
for (name, shape) in tqdm(init_vars, desc='converting tf checkpoint to dict'):
skip_key = any([(pat in name) for pat in ignore_name])
if skip_key:
... |
class AdaptivePadding(nn.Module):
def __init__(self, kernel_size=1, stride=1, dilation=1, padding='corner'):
super(AdaptivePadding, self).__init__()
assert (padding in ('same', 'corner'))
kernel_size = to_2tuple(kernel_size)
stride = to_2tuple(stride)
dilation = to_2tuple(dil... |
def test_loader_no_get_pipeline_definition():
loader_cache.clear()
import sys
current_module = sys.modules[__name__]
pipeline = Pipeline('arb pipe', context_args='arb context input', loader=__name__)
with patch_logger('pypyr.cache.loadercache', logging.ERROR) as mock_logger_error:
with pytes... |
def main(args):
device = 'cuda'
print('Loading ResNext101 model...')
model = nn.DataParallel(resnet101(sample_duration=16).cuda())
model.load_state_dict(torch.load('resnext-101-kinetics.pth')['state_dict'])
print('Loading video paths...')
if (args.dataset == 'uva'):
files = glob.glob((ar... |
def make_vgg_layer(inplanes, planes, num_blocks, dilation=1, with_bn=False, ceil_mode=False):
layers = []
for _ in range(num_blocks):
layers.append(conv3x3(inplanes, planes, dilation))
if with_bn:
layers.append(nn.BatchNorm2d(planes))
layers.append(nn.ReLU(inplace=True))
... |
class TestNodeFinder():
def test_straightforward(self):
class MyType(Type):
def __init__(self, name):
self.name = name
def filter(self, *args, **kwargs):
raise NotImplementedError()
def __str__(self):
return self.name
... |
def gen_efficientnet_lite_kwargs(channel_multiplier=1.0, depth_multiplier=1.0, drop_rate=0.2):
arch_def = [['ds_r1_k3_s1_e1_c16'], ['ir_r2_k3_s2_e6_c24'], ['ir_r2_k5_s2_e6_c40'], ['ir_r3_k3_s2_e6_c80'], ['ir_r3_k5_s1_e6_c112'], ['ir_r4_k5_s2_e6_c192'], ['ir_r1_k3_s1_e6_c320']]
model_kwargs = dict(block_args=dec... |
class AlbertTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__(self, vocab_file, do_lower_case=True, remove_space=True, keep_accents=False, bos_token='[C... |
class ObjectDetectionEvaluation():
def __init__(self, num_gt_classes, matching_iou_threshold=0.5, nms_iou_threshold=1.0, nms_max_output_boxes=10000, recall_lower_bound=0.0, recall_upper_bound=1.0, use_weighted_mean_ap=False, label_id_offset=0, group_of_weight=0.0, per_image_eval_class=PerImageEvaluation):
i... |
def write_ppm(im, filename):
magic = 'P6\n'
maxval = 255
w = len(im)
h = len(im[0])
with open(filename, 'w', encoding='latin1', newline='') as fp:
fp.write(magic)
fp.write(('%i %i\n%i\n' % (w, h, maxval)))
for j in range(h):
for i in range(w):
val ... |
def test(args):
inputs = tf.placeholder(tf.float32, (1, 2048, 3))
gt = tf.placeholder(tf.float32, (1, args.num_gt_points, 3))
reconstruction = tf.placeholder(tf.float32, (1, (args.step_ratio * 1024), 3))
is_training_pl = tf.placeholder(tf.bool, shape=(), name='is_training')
mean_feature = tf.placeho... |
class Delta(Distribution):
def dim(self):
return 0
def kl_sym(self, old_dist_info_vars, new_dist_info_vars):
return None
def kl(self, old_dist_info, new_dist_info):
return None
def likelihood_ratio_sym(self, x_var, old_dist_info_vars, new_dist_info_vars):
raise NotImpleme... |
class InputsAndButtonsDemo(ttk.Frame):
def __init__(self, parent):
super().__init__(parent, style='Card.TFrame', padding=15)
self.columnconfigure(0, weight=1)
self.add_widgets()
def add_widgets(self):
self.entry = ttk.Entry(self)
self.entry.insert(0, 'Type here')
... |
class BaseMultiLocation(MacroElement):
def __init__(self, locations: TypeMultiLine, popup: Union[(Popup, str, None)]=None, tooltip: Union[(Tooltip, str, None)]=None):
super().__init__()
self.locations = validate_multi_locations(locations)
if (popup is not None):
self.add_child((p... |
def _enter_pdb(node: Node, excinfo: ExceptionInfo[BaseException], rep: BaseReport) -> BaseReport:
tw = node.config.pluginmanager.getplugin('terminalreporter')._tw
tw.line()
showcapture = node.config.option.showcapture
for (sectionname, content) in (('stdout', rep.capstdout), ('stderr', rep.capstderr), (... |
def convert_all_sentencepiece_models(model_list=None, repo_path=None, dest_dir=Path('marian_converted')):
save_dir = Path('marian_ckpt')
dest_dir = Path(dest_dir)
dest_dir.mkdir(exist_ok=True)
save_paths = []
if (model_list is None):
model_list: list = make_registry(repo_path=repo_path)
... |
def save_image(img, img_path, antialias=True, auto_open=False):
imgSize = (img.getbbox()[2], img.getbbox()[3])
if antialias:
size = (int((imgSize[0] * 0.5)), int((imgSize[1] * 0.5)))
img.thumbnail(size, Image.LANCZOS)
img.save(img_path)
if auto_open:
os.startfile(img_path) |
class QuackCounter(Quackable):
duck: Quackable
numberOfQuacks: List[int] = [0]
def __init__(self, duck: Quackable):
self.duck = duck
def quack(self) -> None:
self.duck.quack()
self.numberOfQuacks[0] += 1
def getQuacks() -> int:
return QuackCounter.numberOfQuacks[0]
... |
class User():
def __init__(self, username, password=None, admin=False):
self.username = username
if (password is not None):
self.encodeAndSetPassword(password)
self.admin = admin
def encodeAndSetPassword(self, pw):
h = hashlib.new('sha256')
salt = ''.join([ran... |
class Podcasts(Browser):
__feeds = Gtk.ListStore(object)
headers = 'title artist performer ~people album date website language copyright organization license contact'.split()
name = _('Podcasts')
accelerated_name = _('_Podcasts')
keys = ['AudioFeeds', 'Podcasts']
priority = 20
uses_main_libr... |
class UpResBlock(nn.Module):
def __init__(self, in_channel):
super(UpResBlock, self).__init__()
self.body = nn.Sequential(nn.Conv2d(in_channel, in_channel, 3, 1, 1), nn.LeakyReLU(0.2, True), nn.Conv2d(in_channel, in_channel, 3, 1, 1))
def forward(self, x):
out = (x + self.body(x))
... |
class test_pgpass(unittest.TestCase):
def runTest(self):
sample1 = client_pgpass.parse(StringIO(passfile_sample))
sample2 = client_pgpass.parse(StringIO(difficult_passfile_sample))
for (k, pw) in passfile_sample_map.items():
lpw = client_pgpass.lookup_password(sample1, k)
... |
class KnownValues(unittest.TestCase):
def test_from_fcivec(self):
myci = scf.UHF(gto.M()).apply(ci.CISD)
(nocca, noccb) = nelec = (3, 2)
(nvira, nvirb) = (5, 6)
myci.nocc = nocc = (nocca, noccb)
nmo = 8
myci.nmo = (nmo, nmo)
numpy.random.seed(12)
civec... |
def test_ellipsoid__semi_minor_not_computed():
cc = CRS('+proj=geos +lon_0=-89.5 +a=6378137.0 +b=6356752.31 h=12345')
assert (cc.datum.ellipsoid.semi_minor_metre == 6356752.31)
assert (cc.datum.ellipsoid.semi_major_metre == 6378137.0)
assert (not cc.datum.ellipsoid.is_semi_minor_computed) |
(number=strategies.integers(min_value=1), base=strategies.integers(min_value=2))
(number=125, base=5)
def test_ceil_log_hypothesis(number, base):
exponent = utils.ceil_log(number, base)
assert ((base ** exponent) >= number)
if (exponent > 1):
assert ((base ** (exponent - 1)) < number) |
def load_clip_to_cpu(cfg):
backbone_name = cfg.MODEL.BACKBONE.NAME
url = clip._MODELS[backbone_name]
model_path = clip._download(url)
try:
model = torch.jit.load(model_path, map_location='cpu').eval()
state_dict = None
except RuntimeError:
state_dict = torch.load(model_path, ... |
class TestEnsureParentDirFunc(unittest.TestCase):
def setUp(self):
self._temp_dir = tempfile.TemporaryDirectory()
def tearDown(self):
self._temp_dir.cleanup()
def test(self):
path1 = os.path.join(self._temp_dir.name, 'sub', 'dir')
path2 = os.path.join(path1, 'file.txt')
... |
def _migrate_v19(preset: dict) -> dict:
if (preset['game'] == 'cave_story'):
itemconfig = preset['configuration']['major_items_configuration']['items_state']
ammoconfig = preset['configuration']['ammo_configuration']['items_state']
if (itemconfig.get('Base Missiles') is not None):
... |
class TestElasticSearchCollector(CollectorTestCase):
def setUp(self):
config = get_collector_config('ElasticSearchCollector', {})
self.collector = ElasticSearchCollector(config, None)
def test_import(self):
self.assertTrue(ElasticSearchCollector)
def test_new__instances_default(self)... |
def queue_tool() -> None:
import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument('--max-messages', type=int, default=10, help='if creating the queue, what to set the maximum queue length to')
parser.add_argument('--max-message-size', type=int, default=8096, help='if creati... |
class ACE():
def __init__(self):
pass
def from_bytes(data, sd_object_type=None):
return ACE.from_buffer(io.BytesIO(data), sd_object_type)
def from_buffer(buff, sd_object_type=None):
hdr = ACEHeader.pre_parse(buff)
obj = acetype2ace.get(hdr.AceType)
if (not obj):
... |
class Tracklet_3D(object):
def __init__(self, label_file):
(lines, num_lines) = load_txt_file(label_file)
self.data = dict()
for line in lines:
self.load_line(line)
def load_line(self, line):
line = line.split(' ')
obj_type = line[2]
frame = int(line[0... |
class RemoteTempFileTests(ProvyTestCase):
def any_context(self):
return {'used_roles': {}}
def setUp(self):
super(RemoteTempFileTests, self).setUp()
self.instance = Role(None, self.any_context())
self.patcher = patch('provy.core.roles.Role.remote_temp_dir', Mock(return_value='/tm... |
def test_requirement_source_disable_pip_editable_without_egg_fragment(req_file):
source = _init_requirement([(req_file(), '-e file:flask.py')], disable_pip=True, no_deps=True)
specs = list(source.collect())
assert (SkippedDependency(name='-e file:flask.py', skip_reason='could not deduce package version from... |
class BatchMiner():
def __init__(self, opt):
self.par = opt
self.name = 'semihard'
self.margin = vars(opt)[(('loss_' + opt.loss) + '_margin')]
def __call__(self, batch, labels, return_distances=False):
if isinstance(labels, torch.Tensor):
labels = labels.detach().nump... |
def scheduler_init(app):
if (platform.system() != 'Windows'):
fcntl = __import__('fcntl')
f = open('scheduler.lock', 'wb')
try:
fcntl.flock(f, (fcntl.LOCK_EX | fcntl.LOCK_NB))
scheduler.init_app(app)
scheduler.start()
app.logger.debug('Schedule... |
def RaisesOp(context, exceptionClass, indent, kws, arglist, node):
exceptionClass.prefix = ''
args = [exceptionClass]
if ('expected_regex' in kws):
expected_regex = kws.get('expected_regex').clone()
expected_regex.prefix = ''
args.append(String(', '))
args.append(KeywordArg(N... |
def encode_images(device, G, encoder, dlatent_avg, images, truncation_psi, num_steps):
lpips_model = stylegan2.external_models.lpips.LPIPS_VGG16(pixel_min=(- 1), pixel_max=1)
proj = stylegan2.project.Projector(G=G, dlatent_avg_samples=10000, dlatent_avg_label=None, dlatent_device=device, dlatent_batch_size=1024... |
def autoencode_eval(gts, res, eval_lang='en'):
assert isinstance(gts, (list, tuple))
assert isinstance(res, (list, tuple))
assert (len(gts) == len(res))
if (eval_lang == 'zh'):
gts = {i: [tokenize_zh_sentence(item)] for (i, item) in enumerate(gts)}
res = {i: [tokenize_zh_sentence(''.join... |
def run_gat_surrogate(args, device, data, model_filename):
(in_feats, n_classes, train_g, val_g, test_g, target_response) = data
train_nid = train_g.nodes()
val_nid = val_g.nodes()
test_nid = test_g.nodes()
n_output_dim = target_response.shape[1]
print('output dim is: ', n_output_dim)
sample... |
def get_vtm_decoder_path(build_dir):
system = platform.system()
try:
elfnames = {'Darwin': 'DecoderApp', 'Linux': 'DecoderAppStatic'}
return os.path.join(build_dir, elfnames[system])
except KeyError as err:
raise RuntimeError(f'Unsupported platform "{system}"') from err |
class SimpleUser(msgspec.Struct, omit_defaults=True):
login: str
id: int
node_id: str
avatar_url: str
gravatar_id: Optional[str]
url: str
html_url: str
followers_url: str
following_url: str
gists_url: str
starred_url: str
subscriptions_url: str
organizations_url: str
... |
def load_diverse_ensemble_for_inference(filenames: List[str], task: Optional[tasks.FairseqTask]=None):
checkpoints_data = []
for filename in filenames:
if (not PathManager.exists(filename)):
raise IOError('Model file not found: {}'.format(filename))
with PathManager.open(filename, 'r... |
class Server(QDialog):
FORTUNES = ("You've been leading a dog's life. Stay off the furniture.", "You've got to think about tomorrow.", 'You will be surprised by a loud noise.', 'You will feel hungry again in another hour.', 'You might have mail.', 'You cannot kill time without injuring eternity.', 'Computers are no... |
def getTurbulenceVariables(solverSettings):
turbulenceModelName = solverSettings['turbulenceModel']
viscosity_var = getTurbulentViscosityVariable(solverSettings)
if (turbulenceModelName in ['laminar', 'invisid', 'DNS']):
var_list = []
elif (turbulenceModelName in kEpsilon_models):
var_li... |
class SignalConnection(gui.HBox):
def __init__(self, widget, listenersList, eventConnectionFuncName, eventConnectionFunc, **kwargs):
super(SignalConnection, self).__init__(**kwargs)
self.style.update({'overflow': 'visible', 'height': '24px', 'outline': '1px solid lightgray'})
self.label = gu... |
def check_workers_alive_and_busy(export_pool: Pool, worker_list: List, results_list: List, allowed_num_queued: int=0):
alive = [i.is_alive() for i in worker_list]
if (not all(alive)):
raise RuntimeError('Some background workers are no longer alive')
not_ready = [(not i.ready()) for i in results_list... |
class OverlayProvider(StaticProvider):
def __init__(self, overlays: Iterable[Overlay], chain: Optional[Chain]):
self._chain = chain
self._overlays = ClassMap(*overlays)
_provision_action
def _provide_overlay(self, mediator: Mediator, request: OverlayRequest):
try:
overlay... |
def compute_target(answers_dset, ans2label, name, cache_root):
target = []
for ans_entry in answers_dset:
answers = ans_entry['answers']
answer_count = {}
for answer in answers:
answer_ = answer['answer']
answer_count[answer_] = (answer_count.get(answer_, 0) + 1)
... |
def panfpn_config(min_level, max_level, weight_method=None):
p = OmegaConf.create()
weight_method = (weight_method or 'fastattn')
num_levels = ((max_level - min_level) + 1)
node_ids = {(min_level + i): [i] for i in range(num_levels)}
level_last_id = (lambda level: node_ids[level][(- 1)])
id_cnt ... |
def parse(string, symb=None):
if (symb is not None):
symb = _std_symbol(symb)
raw_data = string.splitlines()
for (i, dat) in enumerate(raw_data):
dat0 = dat.split(None, 1)
if (dat0 and (dat0[0] == symb)):
break
if ((i + 1) == len(raw_data)):
... |
def main():
env = gym.make('Pendulum-v0')
env.seed(args.seed)
agent = Agent()
training_records = []
(running_reward, running_q) = ((- 1000), 0)
for i_ep in range(100):
score = 0
state = env.reset()
for t in range(200):
(action, action_index) = agent.select_act... |
class first_conv(nn.Conv2d):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False):
super(first_conv, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias)
self.layer_type = 'FConv2d'
def forwar... |
def build_transform(is_train, args):
resize_im = (args.input_size > 32)
imagenet_default_mean_and_std = args.imagenet_default_mean_and_std
mean = (IMAGENET_INCEPTION_MEAN if (not imagenet_default_mean_and_std) else IMAGENET_DEFAULT_MEAN)
std = (IMAGENET_INCEPTION_STD if (not imagenet_default_mean_and_st... |
def test_filerewriter_files_in_to_out_no_in_found_no_out():
rewriter = ArbRewriter('formatter')
with patch_logger('pypyr.utils.filesystem', logging.INFO) as mock_logger_info:
rewriter.files_in_to_out('./arb/*')
assert (mock_logger_info.mock_calls == [call('./arb/* found no files')])
assert (not ... |
def eval_where(pred, label):
pred_conds = [unit for unit in pred['where'][::2]]
label_conds = [unit for unit in label['where'][::2]]
label_wo_agg = [unit[2] for unit in label_conds]
pred_total = len(pred_conds)
label_total = len(label_conds)
cnt = 0
cnt_wo_agg = 0
for unit in pred_conds:... |
def add_args_to_env(builder: IRBuilder, local: bool=True, base: ((FuncInfo | ImplicitClass) | None)=None, reassign: bool=True) -> None:
fn_info = builder.fn_info
args = fn_info.fitem.arguments
nb = num_bitmap_args(builder, args)
if local:
for arg in args:
rtype = builder.type_to_rtyp... |
def ddpg_heatmap():
from ddpg import ActorNet, CriticNet
(x_pxl, y_pxl) = (300, 400)
state = torch.Tensor([[np.cos(theta), np.sin(theta), thetadot] for thetadot in np.linspace((- 8), 8, y_pxl) for theta in np.linspace((- np.pi), np.pi, x_pxl)])
anet = ActorNet()
anet.load_state_dict(torch.load('para... |
class InputFeatures(object):
def __init__(self, input_ids, attention_mask, token_type_ids, label, input_len):
self.input_ids = input_ids
self.attention_mask = attention_mask
self.token_type_ids = token_type_ids
self.input_len = input_len
self.label = label
def __repr__(se... |
_model('my_model')
class MyModel(ClassyModel):
def __init__(self):
super().__init__()
self.model = nn.Sequential(nn.AdaptiveAvgPool2d((20, 20)), nn.Flatten(1), nn.Linear(((3 * 20) * 20), 2), nn.Sigmoid())
def forward(self, x):
x = self.model(x)
return x
def from_config(cls, c... |
def wait_single_channel_deposit(app_deposit: 'RaidenService', app_partner: 'RaidenService', registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, total_deposit: TokenAmount, retry_timeout: float) -> None:
wait_for_participant_deposit(raiden=app_deposit, token_network_registry_address=registry_... |
def run_ruff(settings: PluginSettings, document_path: str, document_source: str, subcommand: Subcommand=Subcommand.CHECK, fix: bool=False, extra_arguments: Optional[List[str]]=None) -> str:
executable = settings.executable
arguments = subcommand.build_args(document_path, settings, fix, extra_arguments)
p = ... |
((pgv is None), 'NestedGraph diagram test requires graphviz')
class TestDiagramsNested(TestDiagrams):
machine_cls = HierarchicalGraphMachine
def setUp(self):
super(TestDiagramsNested, self).setUp()
self.states = ['A', 'B', {'name': 'C', 'children': [{'name': '1', 'children': ['a', 'b', 'c']}, '2... |
class KLLoss_t3(nn.Module):
def __init__(self):
super(KLLoss_t3, self).__init__()
def forward(self, pred, label):
T = 3
predict = F.log_softmax((pred / T), dim=1)
target_data = F.softmax((label / T), dim=1)
target_data = (target_data + (10 ** (- 7)))
target = Vari... |
(prefer_attrib=..., dict_factory=one_of(just(dict), just(OrderedDict)), detailed_validation=...)
def test_col_overrides(prefer_attrib: bool, dict_factory: Callable, detailed_validation: bool):
c = Converter(prefer_attrib_converters=prefer_attrib, detailed_validation=detailed_validation, dict_factory=dict_factory, u... |
class LogitGetter(torch.nn.Module):
possible_layer_names = ['fc', 'proxies', 'W']
def __init__(self, classifier, layer_name=None, transpose=None, distance=None, copy_weights=True):
super().__init__()
self.copy_weights = copy_weights
if (layer_name is not None):
self.set_weigh... |
class Problem(qpsolvers.Problem):
name: str
def __init__(self, P: Union[(np.ndarray, spa.csc_matrix)], q: np.ndarray, G: Optional[Union[(np.ndarray, spa.csc_matrix)]], h: Optional[np.ndarray], A: Optional[Union[(np.ndarray, spa.csc_matrix)]], b: Optional[np.ndarray], lb: Optional[np.ndarray], ub: Optional[np.nd... |
def main(args):
print(args)
split_name = ('dev' if args.dev else 'train')
filter_subset = ('spider' if (not args.full_break) else '')
dataset_break = DatasetBreak(args.qdmr_path, split_name, filter_subset=filter_subset)
if (args.break_idx is not None):
qdmr_name = dataset_break.names[args.br... |
def modified_precision(candidate, references, n):
tngrams = ((len(candidate) + 1) - n)
counts = Counter([tuple(candidate[i:(i + n)]) for i in range(tngrams)])
if (len(counts) == 0):
return (0, 0)
max_counts = {}
for reference in references:
rngrams = ((len(reference) + 1) - n)
... |
.parametrize('bounded', [False, True])
def test_mle_jacobian(bounded):
truth = 10.0
rtol = 0.0001
(start, model, _) = models.simple_normal(bounded_prior=bounded)
with model:
map_estimate = find_MAP(method='BFGS', model=model)
assert_allclose(map_estimate['mu_i'], truth, rtol=rtol) |
def _get_win_folder_with_ctypes(csidl_name):
import ctypes
csidl_const = {'CSIDL_APPDATA': 26, 'CSIDL_COMMON_APPDATA': 35, 'CSIDL_LOCAL_APPDATA': 28}[csidl_name]
buf = ctypes.create_unicode_buffer(1024)
ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)
has_high_char = False
... |
def do_checkpoint(prefix, means, stds):
def _callback(iter_no, sym, arg, aux):
arg['bbox_pred_weight_test'] = (arg['bbox_pred_weight'].T * mx.nd.array(stds)).T
arg['bbox_pred_bias_test'] = ((arg['bbox_pred_bias'] * mx.nd.array(stds)) + mx.nd.array(means))
mx.model.save_checkpoint(prefix, (it... |
class FlaxRobertaModelTester(unittest.TestCase):
def __init__(self, parent, batch_size=13, seq_length=7, is_training=True, use_attention_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37, hidden_act='gelu', hidden_dro... |
class MockPsutil(ModuleType):
up = 0
down = 0
def net_io_counters(cls, pernic=False, _nowrap=True):
class IOCounters():
def __init__(self):
self.bytes_sent = 100
self.bytes_recv = 1034
if pernic:
return {'wlp58s0': IOCounters(), 'lo': I... |
class KeepKey_KeyStore(Hardware_KeyStore):
hw_type = 'keepkey'
device = 'KeepKey'
plugin: 'KeepKeyPlugin'
def get_client(self, force_pair=True):
return self.plugin.get_client(self, force_pair)
def decrypt_message(self, sequence, message, password):
raise UserFacingException(_('Encryp... |
class TestForbiddenPythonSyntaxCheckerAllowedsyntax(pylint.testutils.CheckerTestCase):
CHECKER_CLASS = ForbiddenPythonSyntaxChecker
CONFIG = {}
def set_up(self) -> None:
self.setup_method()
def test_allow_break_in_code(self) -> None:
src = '\n for i in range(0, 10):\n b... |
class TestDraw(unittest.TestCase):
def setUp(self):
pass
def click_ax_center(self, m, dx=0, dy=0, release=True, button=1):
ax = m.ax
cv = m.f.canvas
(x, y) = (((ax.bbox.x0 + ax.bbox.x1) / 2), ((ax.bbox.y0 + ax.bbox.y1) / 2))
button_press_event(cv, (x + dx), (y + dy), butt... |
def test_hswish():
act = HSwish(inplace=True)
assert act.act.inplace
act = HSwish()
assert (not act.act.inplace)
input = torch.randn(1, 3, 64, 64)
expected_output = ((input * relu6((input + 3))) / 6)
output = act(input)
assert (output.shape == expected_output.shape)
assert torch.equa... |
class ResidualVectorQuantization(nn.Module):
def __init__(self, *, num_quantizers, **kwargs):
super().__init__()
self.layers = nn.ModuleList([VectorQuantization(**kwargs) for _ in range(num_quantizers)])
def forward(self, x, n_q: tp.Optional[int]=None):
quantized_out = 0.0
residu... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, plan... |
def test_text_format_validation_error_message_simple():
validator = Draft7Validator({'properties': {'foo': {'anyOf': [{'type': 'string'}, {'properties': {'bar': {'type': 'array'}}}]}}})
err = next(validator.iter_errors({'foo': {'bar': 1}}))
text_reporter = TextReporter(verbosity=1)
s1 = text_reporter._f... |
class RNNAgent(nn.Module):
def __init__(self, input_shape, args):
super(RNNAgent, self).__init__()
self.args = args
self.fc1 = nn.Linear(input_shape, args.rnn_hidden_dim)
self.rnn = nn.GRUCell(args.rnn_hidden_dim, args.rnn_hidden_dim)
self.fc2 = nn.Linear(args.rnn_hidden_dim,... |
def test_read_setup_py_simple(tmp_path):
with open((tmp_path / 'setup.py'), 'w') as f:
f.write(dedent('\n from setuptools import setup\n\n setup(\n name = "hello",\n other = 23,\n example = ["item", "other"],\n ... |
class ToolProxy(ToolBase):
def load_tc_profile(self):
response = requests.get(self.tool_consumer_profile_url)
self.tc_profile = json.loads(response.text)
def tool_consumer_profile_url(self):
return self.launch_params['tc_profile_url']
def find_registration_url(self):
for serv... |
.end_to_end()
.parametrize('node_def', ["(PathNode(path=Path('file1.txt')), PathNode(path=Path('file2.txt')))", "(Path('file1.txt'), Path('file2.txt'))"])
def test_return_with_tuple_and_task_decorator(runner, tmp_path, node_def):
source = f'''
from pathlib import Path
from typing_extensions import Annotated... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.