code stringlengths 281 23.7M |
|---|
def _migrate_v17(data: dict) -> dict:
if ('worlds' in data):
data['regions'] = data.pop('worlds')
def _fix(target: dict) -> None:
target['region'] = target.pop('world_name')
target['area'] = target.pop('area_name')
if ('node_name' in target):
target['node'] = target.p... |
def col(name: Optional[str]=None, *, dtype: Optional['DTypeLike']=None, shape: Optional[tuple[(ST, Literal[1])]]=(None, 1)) -> 'TensorVariable':
if (dtype is None):
dtype = config.floatX
shape = _validate_static_shape(shape, ndim=2)
if (shape[1] != 1):
raise ValueError(f'The second dimension... |
_on_failure
.parametrize('number_of_nodes', [1])
.parametrize('channels_per_node', [0])
.parametrize('enable_rest_api', [True])
def test_api_channel_state_change_errors(api_server_test_instance: APIServer, token_addresses, reveal_timeout):
partner_address = '0x61C808D82A3AcdaDc13c777b59310bD9'
token_address = t... |
def test_ignore_anchor_by_class(app, client):
unwanted_urls = {'/page-d'}
selectors_to_ignore = ['a.menu-link-page-d-class']
crawler = Crawler(client=client, initial_paths=['/'], rules=PERMISSIVE_HYPERLINKS_ONLY_RULE_SET, ignore_css_selectors=selectors_to_ignore)
crawler.crawl()
assert (crawler.grap... |
def camel2title(strings: List[str], sep: str=' ', acronyms: Optional[List[str]]=None) -> List[str]:
if (isinstance(strings, str) or (not hasattr(strings, '__iter__'))):
raise TypeError("camel2title() 'strings' argument must be iterable of strings")
if (len(strings) == 0):
return strings
if (... |
def register(actions: List[Action], action: Action, before: Optional[str]=None, after: Optional[str]=None) -> List[Action]:
reference = (before or after or get_id(define_structure))
position = _find(actions, reference)
if (not before):
position += 1
clone = actions[:]
clone.insert(position, ... |
def sort_score(array, indices, comparator=(lambda a, b: (a < b))):
new_indices = [i for i in indices]
swap_count = 0
num_items = len(indices)
for i in range((num_items - 1)):
for j in range(((num_items - i) - 1)):
if (not comparator(array[new_indices[j]], array[new_indices[(j + 1)]])... |
class Attention(nn.Module):
def __init__(self, dim, heads, head_dim, dropout):
super().__init__()
inner_dim = (heads * head_dim)
project_out = (not ((heads == 1) and (head_dim == dim)))
self.heads = heads
self.scale = (head_dim ** (- 0.5))
self.attend = nn.Softmax(dim... |
class StringMap(MappedField, String):
def _deserialize(self, *args: Any, **kwargs: Any) -> Any:
result = super()._deserialize(*args, **kwargs)
return StringMapping(*result)
def _serialize(self, *args: Any, **kwargs: Any) -> Any:
return super()._serialize(*args, **kwargs)
_tuple_field... |
_loss('attention_supervision')
class AttentionSupervisionLoss(nn.Module):
def __init__(self):
super().__init__()
self.loss_fn = (lambda *args, **kwargs: nn.functional.binary_cross_entropy(*args, **kwargs))
def forward(self, sample_list, model_output):
context_attentions = model_output['a... |
def LogisticClassifier(inputs, labels, scope=None, reuse=None):
with tf.variable_scope(scope, 'LogisticClassifier', [inputs, labels], reuse=reuse):
predictions = slim.fully_connected(inputs, 1, activation_fn=tf.sigmoid, scope='fully_connected')
slim.losses.log_loss(predictions, labels)
retur... |
class CLIPTextEmbedding(BaseEmbedding):
def __init__(self, clip_name='ViT-B/32', num_embed=49408, normalize=True, pick_last_embedding=True, keep_seq_len_dim=False, additional_last_embedding=False, embed_dim=1024):
super().__init__()
self.num_embed = num_embed
self.clip_name = clip_name
... |
def api(request, app):
marker = request.node.get_closest_marker('api')
bpkwargs = {}
kwargs = {}
if marker:
if ('prefix' in marker.kwargs):
bpkwargs['url_prefix'] = marker.kwargs.pop('prefix')
if ('subdomain' in marker.kwargs):
bpkwargs['subdomain'] = marker.kwarg... |
class HubSpotOAuth2(BaseOAuth2):
name = 'hubspot'
AUTHORIZATION_URL = '
ACCESS_TOKEN_URL = '
ACCESS_TOKEN_METHOD = 'POST'
USER_DATA_URL = '
DEFAULT_SCOPE = ['oauth']
EXTRA_DATA = [('hub_domain', 'hub_domain'), ('hub_id', 'hub_id'), ('app_id', 'app_id'), ('user_id', 'user_id'), ('refresh_toke... |
class _Ws2(Protocol):
def WSAGetLastError(self) -> int:
...
def WSAIoctl(self, socket: CData, dwIoControlCode: WSAIoctls, lpvInBuffer: AlwaysNull, cbInBuffer: int, lpvOutBuffer: CData, cbOutBuffer: int, lpcbBytesReturned: CData, lpOverlapped: AlwaysNull, lpCompletionRoutine: AlwaysNull, /) -> int:
... |
class Assert(_base_nodes.Statement):
_astroid_fields = ('test', 'fail')
test: NodeNG
fail: (NodeNG | None)
def postinit(self, test: NodeNG, fail: (NodeNG | None)) -> None:
self.fail = fail
self.test = test
def get_children(self):
(yield self.test)
if (self.fail is not... |
class _FIFOReceiver(_MessageReceiver):
def __init__(self):
self.file_name = self._get_file_name()
os.mkfifo(self.file_name)
def _get_file_name(self):
prefix = (tempfile.gettempdir() + '/__rope_')
i = 0
while os.path.exists((prefix + str(i).rjust(4, '0'))):
i +... |
class Bottle(object):
def __init__(self, catchall=True, autojson=True):
self.config = ConfigDict()
self.config._on_change = functools.partial(self.trigger_hook, 'config')
self.config.meta_set('autojson', 'validate', bool)
self.config.meta_set('catchall', 'validate', bool)
sel... |
def rename_and_convert_flax_params(flax_dict):
converted_dict = {}
CONVERSION_MAPPING = {'token_embedder': 'embeddings', 'encoder_norm': 'layernorm', 'kernel': 'weight', '.out': '.output', 'scale': 'weight', 'embedders_0.pos_embedding': 'row_embedder.weight', 'embedders_1.pos_embedding': 'column_embedder.weight... |
class Trainer(object):
def __init__(self, args, model, optim, grad_accum_count=1, n_gpu=1, gpu_rank=1, report_manager=None):
self.args = args
self.save_checkpoint_steps = args.save_checkpoint_steps
self.model = model
self.optim = optim
self.grad_accum_count = grad_accum_count... |
def setup_tent(args, model, logger):
model = tent.configure_model(model)
(params, param_names) = tent.collect_params(model)
optimizer = setup_optimizer(params)
if args.verbose:
logger.debug(f'model for adaptation: %s', model)
logger.debug(f'params for adaptation: %s', param_names)
... |
def normal_init(m, mean, std):
if isinstance(m, (nn.Linear, nn.Conv2d)):
m.weight.data.normal_(mean, std)
if (m.bias.data is not None):
m.bias.data.zero_()
elif isinstance(m, (nn.BatchNorm2d, nn.BatchNorm1d)):
m.weight.data.fill_(1)
if (m.bias.data is not None):
... |
.parametrize('value', [True, False])
def test_memmap_ownership_2pass(value):
t = torch.tensor([1])
m1 = MemmapTensor.from_tensor(t, transfer_ownership=value)
filename = m1.filename
with tempfile.NamedTemporaryFile(suffix='.pkl') as tmp2:
pickle.dump(m1, tmp2)
if value:
assert... |
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
flowLayout = FlowLayout()
flowLayout.addWidget(QPushButton('Short'))
flowLayout.addWidget(QPushButton('Longer'))
flowLayout.addWidget(QPushButton('Different text'))
flowLayout.addWidget(QPushBut... |
.parametrize('pat,txt,segments', [('foo', 'foo', [(0, 3)]), ('foo', 'foobar', [(0, 3)]), ('foo', 'FOObar', [(0, 3)]), ('foo', 'barfoo', [(3, 3)]), ('foo', 'barfoobaz', [(3, 3)]), ('foo', 'barfoobazfoo', [(3, 3), (9, 3)]), ('foo', 'foofoo', [(0, 3), (3, 3)]), ('a b', 'cadb', [(1, 1), (3, 1)]), ('foo', '<foo>', [(1, 3)])... |
def test_account_manager_invalid_directory(caplog):
with patch.object(os, 'listdir') as mock_listdir:
mock_listdir.side_effect = OSError
AccountManager('/some/path')
logs = [('Unable to list the specified directory', '/some/path', '')]
for (msg, path, reason) in logs:
for record in c... |
('/api/data_tool_list', methods=['POST'])
def get_data_tool_list() -> List[dict]:
for (i, tool) in enumerate(DATA_TOOLS):
cache_path = f"backend/static/images/{tool['name']}.cache"
with open(cache_path, 'r') as f:
image_content = f.read()
DATA_TOOLS[i]['icon'] = image_content... |
def delete_all_replicaset_namespace(kubecli: KrknKubernetes, namespace: str):
try:
replicasets = kubecli.get_all_replicasets(namespace)
for replicaset in replicasets:
logging.info(('Deleting replicaset' + replicaset))
kubecli.delete_replicaset(replicaset, namespace)
excep... |
class DescribeCT_Styles():
def it_can_add_a_style_of_type(self, add_fixture):
(styles, name, style_type, builtin, expected_xml) = add_fixture
style = styles.add_style_of_type(name, style_type, builtin)
assert (styles.xml == expected_xml)
assert (style is styles[(- 1)])
(params=[(... |
class PremiumView(discord.ui.View):
def __init__(self, text='This feature requires Quotient Premium.', *, label='Get Quotient Pro'):
super().__init__(timeout=None)
self.text = text
self.add_item(PremiumPurchaseBtn(label=label))
def premium_embed(self) -> discord.Embed:
_e = disco... |
def main(*args, **kwargs):
config = init_job()
config.optimizer.batch_size = 64
LOG.info('Loading data.')
if (config.dataset == 'publaynet'):
val_data = PublaynetLayout(config.val_json, 9, config.cond_type)
elif (config.dataset == 'rico'):
val_data = RicoLayout(config.dataset_path, '... |
def _build_vision_tower(embed_dim: int, vision_cfg: CLIPVisionCfg, quick_gelu: bool=False, cast_dtype: Optional[torch.dtype]=None):
if isinstance(vision_cfg, dict):
vision_cfg = CLIPVisionCfg(**vision_cfg)
act_layer = (QuickGELU if quick_gelu else nn.GELU)
if vision_cfg.eva_model_name:
visio... |
def pytest_collection_modifyitems(items: List[pytest.Item]):
for item in items:
parent = item.parent
if (parent is None):
return
if (parent.name.endswith('WithRequest') and (not parent.get_closest_marker(name='flaky')) and (not parent.get_closest_marker(name='req'))):
... |
class File(Resource):
def __init__(self, project, name):
self.newlines = None
super().__init__(project, name)
def read(self):
data = self.read_bytes()
try:
(content, self.newlines) = fscommands.file_data_to_unicode(data)
return content
except Unico... |
def test_pickup_data_for_pb_expansion_unlocked(echoes_pickup_database, multiworld_item, echoes_resource_database):
pickup = pickup_creator.create_ammo_pickup(echoes_pickup_database.ammo_pickups['Power Bomb Expansion'], [2], False, echoes_resource_database)
creator = pickup_exporter.PickupExporterSolo(patch_data... |
def test_nyquist_basic():
sys = ct.rss(5, 1, 1)
N_sys = ct.nyquist_response(sys)
assert (_Z(sys) == (N_sys + _P(sys)))
A = np.array([[(- 3.), (- 1.), (- 1.5626527), (- 0.4626829), (- 0.)], [(- 8.), (- 3.), (- 3.), (- 0.), 0.], [(- 2.), (- 0.), (- 1.), (- 0.4038419), 0.], [(- 0.281183), 0., 0., (- 0.9771... |
class _ProblemUnitaryToHardwareGraph(cirq.PointOptimizer):
def __init__(self, node_coordinates: List[Tuple[(int, int)]]):
super().__init__()
self._node_coordinates = node_coordinates
def optimize_circuit(self, circuit: cirq.Circuit):
frontier: Dict[(cirq.Qid, int)] = defaultdict((lambda ... |
class calibrate_rudder_feedback(menu):
def __init__(self):
items = [calibrate_rudder_state('reset'), calibrate_rudder_state('centered'), calibrate_rudder_state('starboard range'), calibrate_rudder_state('port range'), ValueEdit(_('range'), _('degrees'), 'rudder.range')]
super(calibrate_rudder_feedba... |
class UnauthedDocumentationLinkAPITests(AuthenticatedAPITestCase):
def setUp(self):
super().setUp()
self.client.force_authenticate(user=None)
def test_detail_lookup_returns_401(self):
url = reverse('api:bot:documentationlink-detail', args=('whatever',))
response = self.client.get... |
class VersionDeclarationABC(ABC):
def __init__(self, path: (Path | str), search_text: str) -> None:
self.path = Path(path)
if (not self.path.exists()):
raise FileNotFoundError(f'path {self.path.resolve()!r} does not exist')
self.search_text = search_text
self._content: (s... |
class ForceReply(TelegramObject):
__slots__ = ('selective', 'force_reply', 'input_field_placeholder')
def __init__(self, selective: Optional[bool]=None, input_field_placeholder: Optional[str]=None, *, api_kwargs: Optional[JSONDict]=None):
super().__init__(api_kwargs=api_kwargs)
self.force_reply:... |
(reahl_system_fixture=ReahlSystemFixture, sql_alchemy_fixture=SqlAlchemyFixture, party_account_fixture=PartyAccountFixture, web_fixture=WebFixture, task_queue_fixture=TaskQueueFixture2)
class WorkflowWebFixture(Fixture):
def new_queues(self):
return [self.task_queue_fixture.queue]
def new_account_bookma... |
def find_median(partition, dim):
frequency = frequency_set(partition, dim)
split_val = ''
next_val = ''
value_list = list(frequency.keys())
value_list.sort(key=cmp_to_key(cmp_value))
total = sum(frequency.values())
middle = (total // 2)
if ((middle < GL_K) or (len(value_list) <= 1)):
... |
def is_checkpoint_phase(mode_num: int, mode_frequency: int, train_phase_idx: int, num_epochs: int, mode: str):
if (mode == 'iteration'):
checkpointing_phase = ((mode_num % mode_frequency) == 0)
elif (mode == 'phase'):
checkpointing_phase = (((mode_num % mode_frequency) == 0) or (train_phase_idx ... |
class CallbackQuery(TelegramObject):
__slots__ = ('game_short_name', 'message', 'chat_instance', 'id', 'from_user', 'inline_message_id', 'data')
def __init__(self, id: str, from_user: User, chat_instance: str, message: Optional[Message]=None, data: Optional[str]=None, inline_message_id: Optional[str]=None, game... |
def get_trainval_datasets(tag, resize):
if (tag == 'aircraft'):
return (AircraftDataset(phase='train', resize=resize), AircraftDataset(phase='val', resize=resize))
elif (tag == 'bird'):
return (BirdDataset(phase='train', resize=resize), BirdDataset(phase='val', resize=resize))
elif (tag == '... |
def train(RL):
total_steps = 0
observation = env.reset()
while True:
action = RL.choose_action(observation)
f_action = ((action - ((ACTION_SPACE - 1) / 2)) / ((ACTION_SPACE - 1) / 4))
(observation_, reward, done, info) = env.step(np.array([f_action]))
reward /= 10
RL.... |
class F15_Repo(F14_Repo):
removedKeywords = F14_Repo.removedKeywords
removedAttrs = F14_Repo.removedAttrs
urlRequired = False
def _getParser(self):
op = F14_Repo._getParser(self)
for action in op._actions:
for option in ['--baseurl', '--mirrorlist']:
if (optio... |
def main(options):
if (options['model']['name'] == 'GaLR'):
from layers import GaLR as models
elif (options['model']['name'] == 'GaLR_mca'):
from layers import GaLR_mca as models
else:
raise NotImplementedError
vocab = deserialize_vocab(options['dataset']['vocab_path'])
vocab... |
def getSimilarFighters(fighters, mainFighter):
sMkt = Market.getInstance()
mainGroupID = getattr(sMkt.getGroupByItem(mainFighter.item), 'ID', None)
mainAbilityIDs = set((a.effectID for a in mainFighter.abilities))
similarFighters = []
for fighter in fighters:
if (fighter is mainFighter):
... |
class CalcChangeLocalModuleStatesCommand(wx.Command):
def __init__(self, fitID, mainPosition, positions, click):
wx.Command.__init__(self, True, 'Change Module States')
self.fitID = fitID
self.mainPosition = mainPosition
self.positions = positions
self.click = click
s... |
def commit():
root = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../'))
cmd = "cd {}; git log | head -n1 | awk '{{print $2}}'".format(root)
commit = _exec(cmd)
cmd = 'cd {}; git log --oneline | head -n1'.format(root)
commit_log = _exec(cmd)
return 'commit : {}\n log : {}'.forma... |
_fixtures(WebFixture, DataTableExampleFixture)
def test_editing_an_address(web_fixture, data_table_example_fixture):
fixture = data_table_example_fixture
all_addresses = fixture.create_addresses()
browser = fixture.browser
original_address_name = 'friend 7'
browser.open('/')
browser.click(XPath.... |
def test_invalid_sigma_dir(runner, mocker):
mocker.patch('products.vmware_cb_response.CbResponse._authenticate')
mocked_nested_process_search = mocker.patch('products.vmware_cb_response.CbResponse.nested_process_search')
result = runner.invoke(cli, ['--sigmadir', './nonexistent_dir'])
assert ('Supplied ... |
def test_show_basic_with_installed_packages_single_canonicalized(tester: CommandTester, poetry: Poetry, installed: Repository) -> None:
poetry.package.add_dependency(Factory.create_dependency('foo-bar', '^0.1.0'))
foo_bar = get_package('foo-bar', '0.1.0')
foo_bar.description = 'Foobar package'
installed... |
def test_total_reward_benchmark_simple():
benchmark_results = defaultdict(list)
for (i, task) in enumerate(reward_benchmark.tasks):
env_id = task.env_id
benchmark_results[env_id].append(_benchmark_result_helper(reward_benchmark, env_id=env_id, timestamps=[(i + 2)]))
scores = scoring.benchmar... |
.network
.pypy3323bug
def test_build_package_via_sdist(tmp_dir, package_test_setuptools):
build.__main__.build_package_via_sdist(package_test_setuptools, tmp_dir, ['wheel'])
assert (sorted(os.listdir(tmp_dir)) == ['test_setuptools-1.0.0-py2.py3-none-any.whl', 'test_setuptools-1.0.0.tar.gz']) |
class TestBrightnessTemoperature(unittest.TestCase):
sample_band_10 = np.zeros((5, 5))
output = BrightnessTemperatureLandsat()(sample_band_10)
def test_that_method_returns_tuple(self):
self.assertIsInstance(self.output, tuple)
def test_that_output_and_input_size_equel(self):
self.assertE... |
def test_dict_action():
parser = argparse.ArgumentParser(description='Train a detector')
parser.add_argument('--options', nargs='+', action=DictAction, help='custom options')
args = parser.parse_args(['--options', 'item2.a=a,b', 'item2.b=[(a,b), [1,2], false]'])
out_dict = {'item2.a': ['a', 'b'], 'item2... |
.parametrize(('command', 'expected'), [('', True), ('--dry-run', True), ('--lock', False)])
def test_update_prints_operations(command: str, expected: bool, poetry_with_outdated_lockfile: Poetry, repo: TestRepository, command_tester_factory: CommandTesterFactory) -> None:
tester = command_tester_factory('update', po... |
class MegatronBertForMultipleChoice(MegatronBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.bert = MegatronBertModel(config)
classifier_dropout = 0.2
self.dropout = nn.Dropout(classifier_dropout)
self.classifier = nn.Linear(config.hidden_size, ... |
class TestParser():
def test_valid(self, g3):
(e1, e2, e3) = g3.basis_vectors_lst
assert (g3.parse_multivector('e1') == e1)
assert (g3.parse_multivector('-e1') == (- e1))
assert (g3.parse_multivector('--e1') == e1)
assert (g3.parse_multivector('1.0e2 ^ e1') == (100.0 * e1))
... |
def test_expert_slicing_grid(device=rank):
if (dist.get_world_size() != 4):
return
dgrid = DistributionGrid(expert_slicing_group_size=4)
assert (dgrid.get_expert_slicing_group() is not None)
assert (dgrid.get_expert_slicing_world_size() == 4)
assert (dgrid.get_expert_world_size() == 4)
a... |
class DOConv2d(Module):
__constants__ = ['stride', 'padding', 'dilation', 'groups', 'padding_mode', 'output_padding', 'in_channels', 'out_channels', 'kernel_size', 'D_mul']
__annotations__ = {'bias': Optional[torch.Tensor]}
def __init__(self, in_channels, out_channels, kernel_size, D_mul=None, stride=1, pad... |
class ScaleIntByReal(Bloq):
r_bitsize: int
i_bitsize: int
def signature(self):
return Signature([Register('real_in', self.r_bitsize), Register('int_in', self.i_bitsize), Register('result', self.r_bitsize, side=Side.RIGHT)])
def short_name(self) -> str:
return 'r*i'
def t_complexity(s... |
class RecursionTable():
frames_data: dict[(types.FrameType, dict[(str, Any)])]
function_name: str
_trees: dict[(types.FrameType, Tree)]
def __init__(self, function_name: str) -> None:
self.function_name = function_name
self.frames_data = {}
self._trees = {}
def _get_root(self... |
def test_interconnect_doctest():
P = ct.rss(states=6, name='P', strictly_proper=True, inputs=['u[0]', 'u[1]', 'v[0]', 'v[1]'], outputs=['y[0]', 'y[1]', 'z[0]', 'z[1]'])
C = ct.rss(4, 2, 2, name='C', input_prefix='e', output_prefix='u')
sumblk = ct.summing_junction(inputs=['r', '-y'], outputs='e', dimension=... |
.skipif('sys.platform == "win32" and platform.python_implementation() == "PyPy"')
def test_cov_and_no_cov(testdir):
script = testdir.makepyfile(SCRIPT_SIMPLE)
result = testdir.runpytest('-v', '--cov', '--no-cov', '-n', '1', '-s', script)
assert ('Coverage disabled via --no-cov switch!' not in result.stdout.... |
class LogNormalRV(RandomVariable):
name = 'lognormal'
ndim_supp = 0
ndims_params = [0, 0]
dtype = 'floatX'
_print_name = ('LogNormal', '\\operatorname{LogNormal}')
def __call__(self, mean=0.0, sigma=1.0, size=None, **kwargs):
return super().__call__(mean, sigma, size=size, **kwargs) |
class _TabRenderer():
def __init__(self, size=(36, 24), text=wx.EmptyString, img: wx.Image=None, closeable=True):
self.ctab_left = BitmapLoader.getImage('ctableft', 'gui')
self.ctab_middle = BitmapLoader.getImage('ctabmiddle', 'gui')
self.ctab_right = BitmapLoader.getImage('ctabright', 'gui'... |
def lru_cache(maxsize=128, key_fn=None):
def decorator(fn):
cache = LRUCache(maxsize)
argspec = inspect.getfullargspec(fn)
arg_names = (argspec.args[1:] + argspec.kwonlyargs)
kwargs_defaults = get_kwargs_defaults(argspec)
cache_key = key_fn
if (cache_key is None):
... |
def test_set_validation():
c = Converter(detailed_validation=True)
with pytest.raises(IterableValidationError) as exc:
c.structure({'1', 2, 'a'}, Set[int])
assert (repr(exc.value.exceptions[0]) == repr(ValueError("invalid literal for int() with base 10: 'a'")))
assert (exc.value.exceptions[0].__... |
def custom_configure_my_dynamics(ocp: OptimalControlProgram, nlp: NonLinearProgram):
ConfigureProblem.configure_q(ocp, nlp, as_states=True, as_controls=False)
ConfigureProblem.configure_qdot(ocp, nlp, as_states=True, as_controls=False)
ConfigureProblem.configure_tau(ocp, nlp, as_states=False, as_controls=Tr... |
def test_overload() -> None:
overloads = get_overloads('pyanalyze.test_extensions.f')
assert (len(overloads) == 2)
assert all_of_type(overloads, FunctionType)
assert (f not in overloads)
assert (overloads[0].__code__.co_argcount == 0)
assert (overloads[1].__code__.co_argcount == 1)
method_ov... |
def convert_weight_and_push(hidden_sizes: int, name: str, config: LevitConfig, save_directory: Path, push_to_hub: bool=True):
print(f'Converting {name}...')
with torch.no_grad():
if (hidden_sizes == 128):
if (name[(- 1)] == 'S'):
from_model = timm.create_model('levit_128s', p... |
def threading_task(func):
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
futures = []
for (index, ck) in enumerate(ck_list):
if (not ck_signal_list[index]):
continue
task = ZhongFen(ck, index)
task_func = getattr(t... |
def optimize_storage(do_compare, do_record, threshold, use_threshold, data_part_distance, learning_percent, distribution):
store_path = storePath[distribution]
to_store_path = toStorePath[distribution]
tmp_data = pd.read_csv(store_path, header=None)
train_set_x = []
train_set_y = []
test_set_x =... |
class _DummyBosonicDriver(BaseDriver):
def __init__(self):
super().__init__()
modes = [[, 1, 1], [(- ), (- 1), (- 1)], [, 2, 2], [(- ), (- 2), (- 2)], [(- 89.), 2, 1, 1], [(- 15.), 2, 2, 2], [1., 1, 1, 1, 1], [5., 2, 2, 1, 1], [0., 2, 2, 2, 2]]
self._watson = WatsonHamiltonian(modes, 2)
... |
class GrantResource(ModelResource):
search_field = 'user_id'
age_group = Field()
email = Field()
has_sent_submission = Field()
submission_title = Field()
submission_tags = Field()
submission_admin_link = Field()
submission_pycon_link = Field()
grant_admin_link = Field()
USERS_SUB... |
class DescribeRequiredAttribute():
def it_adds_a_getter_property_for_the_attr_value(self, getter_fixture):
(parent, reqAttr_python_value) = getter_fixture
assert (parent.reqAttr == reqAttr_python_value)
def it_adds_a_setter_property_for_the_attr(self, setter_fixture):
(parent, value, exp... |
def get_pqsource_list(prob_label):
sg_ds = [1, 5, 10, 15]
gmd_ds = [5, 20, 40, 60]
gmd_d10_ms = [0, 0.02, 0.04, 0.06]
gvinc_d1_vs = [1, 1.5, 2, 2.5]
gvinc_d5_vs = [1, 1.5, 2, 2.5]
gvsub1_d1_vs = [0.1, 0.3, 0.5, 0.7]
gvd_ds = [1, 5, 10, 15]
gb_rbm_dx50_dh10_stds = [0, 0.02, 0.04, 0.06]
... |
def load_net(data_path):
data = scipy.io.loadmat(data_path)
if (not all(((i in data) for i in ('layers', 'classes', 'normalization')))):
raise ValueError("You're using the wrong VGG19 data. Please follow the instructions in the README to download the correct data.")
mean = data['normalization'][0][0... |
def sa_zaleplon_with_other_formula() -> GoalDirectedBenchmark:
specification = uniform_specification(1, 10, 100)
benchmark_object = zaleplon_with_other_formula()
sa_biased = ScoringFunctionSAWrapper(benchmark_object.objective, SAScoreModifier())
return GoalDirectedBenchmark(name='SA_zaleplon', objective... |
def wrap_mangling_directive(base_directive, objtype):
class directive(base_directive):
def run(self):
env = self.state.document.settings.env
name = None
if self.arguments:
m = re.match('^(.*\\s+)?(.*?)(\\(.*)?', self.arguments[0])
name = m.... |
def get_tokenizer(text, tokenizer, max_length):
token_list = tokenizer(list(text), add_special_tokens=True, max_length=max_length, pad_to_max_length=True, return_tensors='pt')
if (random.random() < 0.5):
(mask_text, _) = mask_tokens(token_list['input_ids'], tokenizer)
token_list['input_ids'] = m... |
class Effect8478(BaseEffect):
type = 'passive'
def handler(fit, skill, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: (mod.item.requiresSkill('Ice Harvesting') or mod.item.requiresSkill('Mining'))), 'duration', skill.getModifiedItemAttr('iceHarvestCycleBonus'), **kwargs) |
class Reveal():
def __init__(self):
self.r = run.Run()
return
def get_parent(self, path):
return os.path.normpath(os.path.join(path, os.pardir))
def reveal(self, path, new_window=False):
if (not (sys.platform == 'darwin')):
return ('', 'macOS Only', 1)
if ... |
def cv(datasetId=None, network=None, nGPU=None, subTorun=None):
datasetId = (datasetId or 0)
network = (network or 'FBCNet')
nGPU = (nGPU or 0)
subTorun = (subTorun or None)
selectiveSubs = False
datasets = ['bci42a', 'korea']
config = {}
config['preloadData'] = False
config['randSee... |
def add_log_related_args(parser: argparse.ArgumentParser):
parser.add_argument('-v', '--verbose', action='store_const', const=logging.INFO, dest='log_level', help='show additional information about current actions')
parser.add_argument('-vv', '--very-verbose', action='store_const', const=logging.DEBUG, dest='lo... |
class TestPolygonZ():
def test_pack(self):
record = {'BBOX Xmin': 0.0, 'BBOX Xmax': 10.0, 'BBOX Ymin': 0.0, 'BBOX Ymax': 10.0, 'NumPoints': 4, 'NumParts': 1, 'Vertices': [(0.0, 0.0), (10.0, 10.0), (10.0, 0.0), (0.0, 0.0)], 'Shape Type': 15, 'Parts Index': [0], 'Zmin': 0, 'Zmax': 10, 'Zarray': [0, 10, 0, 0],... |
def main(args):
assert ((len(args) == 2) and isinstance(args[1], str))
dataset_name = args[1]
logger.info('Using dataset: {}'.format(dataset_name))
tf.set_random_seed(1234)
coord_add = get_coord_add(dataset_name)
dataset_size = get_dataset_size_train(dataset_name)
num_classes = get_num_class... |
class TestMatrix(TestCase):
def setUp(self):
self.A = np.array([[1, 2, 0], [0, 1, 0], [0, 0, 1]])
self.x = np.array([1, 2, 3])
self.mat = pybamm.Matrix(self.A)
self.vect = pybamm.Vector(self.x)
def test_array_wrapper(self):
self.assertEqual(self.mat.ndim, 2)
self.... |
def test_columnize_array():
assert (columnize(list(range(12)), opts={'displaywidth': 6, 'arrange_array': True}) == _strip('\n[ 0,\n 1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n 8,\n 9,\n 10,\n 11]\n\n '))
assert (columnize(list(range(12)), opts={'displaywidth': 10, 'arrange_array': True}) == _strip('\n[ 0... |
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--hostname', type=str, default=DEFAULT_HOSTNAME, help='server hostname')
parser.add_argument('--port', type=int, default=DEFAULT_PORT, help='server port number')
parser.add_argument('--agent-type', default='simul_trans_text', help='... |
class LazyProxyTestCase(unittest.TestCase):
def test_proxy_caches_result_of_function_call(self):
self.counter = 0
def add_one():
self.counter += 1
return self.counter
proxy = support.LazyProxy(add_one)
assert (proxy.value == 1)
assert (proxy.value == 1... |
def _get_or_create_logger(destination: str='null') -> logging.Logger:
global _events_logger
if _events_logger:
return _events_logger
logging_handler = get_logging_handler(destination)
logging_handler.setLevel(logging.DEBUG)
_events_logger = logging.getLogger(f'torchx-events-{destination}')
... |
class Bleu():
def __init__(self, n=4):
self._n = n
self._hypo_for_image = {}
self.ref_for_image = {}
def compute_score(self, gts, res):
assert (sorted(gts.keys()) == sorted(res.keys()))
imgIds = sorted(gts.keys())
bleu_scorer = BleuScorer(n=self._n)
for id... |
def sign_file(file, top_dir=top_dir):
signature_file = os.path.join(top_dir, signatures_dir, (file + '.sig'))
file = os.path.join(top_dir, file)
os.makedirs(os.path.dirname(signature_file), exist_ok=True)
gpg_command('--detach-sig', '-o', signature_file, file)
return signature_file[(len(top_dir) + 1... |
_module()
class LmbdaScheduler(BaseScheduler):
def __init__(self, lmbda, init_values=None):
super(LmbdaScheduler, self).__init__(init_values)
self.lmbda = lmbda
def get(self, init_values=None, niter=None):
niter = (self.niter if (niter is None) else niter)
if (self.init_values is... |
def test_reapply():
l_in1 = InputLayer([None, 10], T.zeros([5, 10]))
l_d1 = DenseLayer(l_in1, 20)
l_d2 = DenseLayer(l_in1, 30)
l_cat = ConcatLayer([l_d1, l_d2])
l_d3 = DenseLayer(l_cat, 20)
l_in2 = InputLayer([None, 10], T.zeros([5, 10]))
new_l_d3 = reapply(l_d3, {l_in1: l_in2})
get_outp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.