code stringlengths 281 23.7M |
|---|
def replaceInternalLinks(text):
cur = 0
res = ''
for (s, e) in findBalanced(text):
m = tailRE.match(text, e)
if m:
trail = m.group(0)
end = m.end()
else:
trail = ''
end = e
inner = text[(s + 2):(e - 2)]
pipe = inner.find... |
def triplet_to_binary(triplet_data):
ret = []
for example in triplet_data:
anchor = example['anchor']
pos = example['positive']
neg = example['negative']
ret.append({'entity_a': anchor, 'entity_b': pos, 'label': 1})
ret.append({'entity_a': anchor, 'entity_b': neg, 'label'... |
def RandomForest(filename, x_predict, model_name, RF_outputname, set_now, game_name, change_side):
data = pd.read_csv(filename)
data = data[needed]
data.dropna(inplace=True)
data = data[(data.type != '')]
data = data[(data.type != '')]
data = data[(data.type != '')]
data = data[(data.type !=... |
def sorted_tests(min_line: int=1, max_line: int=1000, min_length: int=10, max_length: int=12):
return lists(builds(Test, line=integers(min_value=min_line, max_value=max_line).map((lambda line: (line * 2)))), min_size=min_length, max_size=max_length, unique_by=(lambda test: test.line)).map((lambda tests: sorted(test... |
class AnonEnv():
list_intersection_id = ['intersection_1_1']
def __init__(self, path_to_log, path_to_work_directory, dic_traffic_env_conf):
self.path_to_log = path_to_log
self.path_to_work_directory = path_to_work_directory
self.dic_traffic_env_conf = dic_traffic_env_conf
self.si... |
class EngineFromConfigTests(unittest.TestCase):
def setUp(self):
secrets = FakeSecretsStore({'secrets': {'secret/sql/account': {'type': 'credential', 'username': 'reddit', 'password': 'password'}}})
self.secrets = secrets
def test_url(self):
engine = engine_from_config({'database.url': '... |
def display_pedigree(ds: xr.Dataset, parent: Hashable=variables.parent, graph_attrs: Optional[Dict[(Hashable, str)]]=None, node_attrs: Optional[Dict[(Hashable, ArrayLike)]]=None, edge_attrs: Optional[Dict[(Hashable, ArrayLike)]]=None) -> Any:
try:
from graphviz import Digraph
except ImportError:
... |
class TestEntropySchemeStaticGrid():
def test_model_with_entropy_scheme(self):
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.conv1 = torch.nn.Conv2d(3, 16, 3, padding='same')
self.conv2 = torch.nn.Conv2d(16, 16, 3, ... |
def char_padding(inputs, voca_size, embedding_dim, wordMaxLen, charMaxLen):
sentences_embed = list()
sentences_embed_len = list()
for (senIdx, sentence) in enumerate(inputs):
inputs_embed = list()
inputs_embed_len = list()
for (wordIdx, words) in enumerate(sentence):
word... |
def test_model(ds1000: DS1000Dataset, model: str, mode: str, num_procs: int=16, output_dir: Union[(str, Path)]='codex_greedy_outputs'):
check_cpu_count(num_procs)
score = defaultdict(list)
for lib in ds1000.libs:
lib_results = []
problem_code_pairs = []
for problem_id in range(len(ds... |
class TrainSet(torch.utils.data.Dataset):
def __init__(self, data_root, image_size):
super().__init__()
self.transform = transforms.Compose([transforms.Resize(image_size), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
self.imgs = torchvision.datasets.ImageFo... |
class StandardScheme(VersionSchemeInterface):
PLUGIN_NAME = 'standard'
def update(self, desired_version: str, original_version: str, version_data: dict) -> str:
from packaging.version import Version
original = Version(original_version)
versions = desired_version.split(',')
for ve... |
.parametrize('coords,expected', [((0, 1), (1, 0)), (([0], [1]), ([1], [0])), ((0, [1]), ([1], [0])), (([0], 1), ([1], [0])), (([0, 1], [2, 3]), ([2, 3], [0, 1])), ((0, [1, 2]), ([1, 2], [0, 0])), (([0, 1], 2), ([2, 2], [0, 1])), (([0], [1, 2]), ([1, 2], [0, 0])), (([0, 1], [2]), ([2, 2], [0, 1]))])
def test_ensure_arr_... |
class DataTrainingArguments():
task_name: Optional[str] = field(default=None, metadata={'help': ('The name of the task to train on: ' + ', '.join(task_to_keys.keys()))})
dataset_name: Optional[str] = field(default=None, metadata={'help': 'The name of the dataset to use (via the datasets library).'})
dataset... |
def check_relevancy(file, relevant_if_metadata_above, relevant_if_metadata_below, verbose=True, key='default', engine='guess'):
if (engine == 'guess'):
engine = DataFileManager.guess_engine(file)
manager = DataFileManager(engine)
file_metadata = manager.read_metadata(file, key=key)
for (k, v) in... |
_pipeline_test
class ZeroShotClassificationPipelineTests(unittest.TestCase, metaclass=PipelineTestCaseMeta):
model_mapping = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
tf_model_mapping = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
def get_test_pipeline(self, model, tokenizer, feature_extractor):
cla... |
def prepare_collect_config(option, opt):
if (not os.path.exists(opt.collect_path)):
os.makedirs(opt.collect_path)
names = [option['dataset'], option['method'], opt.evaluation_mode]
if opt.not_only_best_candidate:
names.insert(0, 'nobc')
if (option['decoding_type'] == 'ARFormer'):
... |
def SetPyKeyVal(key_name, value_name, value):
root_hkey = get_root_hkey()
root_key = winreg.OpenKey(root_hkey, root_key_name)
try:
my_key = winreg.CreateKey(root_key, key_name)
try:
winreg.SetValueEx(my_key, value_name, 0, winreg.REG_SZ, value)
finally:
my_key... |
class DirectionalLightHelper(Line):
def __init__(self, ray_length=1, color=None, show_shadow_extent=False):
self._color = color
super().__init__(Geometry(positions=np.zeros((8, 3), np.float32)), LineArrowMaterial(color='#fff', thickness=5))
self._shadow_helper = Line(Geometry(positions=np.ze... |
class WireLabel():
def __init__(self, text, count):
self.text = text
self.num_wires = count
self.positions_seen = []
self.tops_seen = []
self.wires_seen = []
self.bottoms_seen = []
self.colors_seen = []
self.info_seen = []
self.ready = 0
... |
def test_prefix():
assert ((TABLE_PREFIX + b'_') == connection._table_name(''))
assert ((TABLE_PREFIX + b'_foo') == connection._table_name('foo'))
assert (connection.table('foobar').name == (TABLE_PREFIX + b'_foobar'))
assert (connection.table('foobar', use_prefix=False).name == b'foobar')
c = Conne... |
class Water_density_fitting(unittest.TestCase):
def setUpClass(cls):
mol = gto.Mole()
mol.verbose = 4
mol.output = '/dev/null'
mol.atom = '\n O 0.00000 0.00000 0.11779\n H 0.00000 0.75545 -0.47116\n H 0.00000 ... |
class RoundRobinArbiterEn(Component):
def construct(s, nreqs):
nreqsX2 = (nreqs * 2)
Type = mk_bits(nreqs)
s.en = InPort()
s.reqs = InPort(Type)
s.grants = OutPort(Type)
s.priority_en = Wire()
s.priority_reg = m = RegEnRst(mk_bits(nreqs), reset_value=1)
... |
def test_AddValueToZero_simple_both():
dm = skcriteria.mkdm(matrix=[[1, 0, 3], [0, 5, 6]], objectives=[min, max, min], weights=[1, 2, 0])
expected = skcriteria.mkdm(matrix=[[1.5, 0.5, 3], [0.5, 5.5, 6]], objectives=[min, max, min], weights=[1.5, 2.5, 0.5])
scaler = AddValueToZero(value=0.5, target='both')
... |
class CmdCombatHelp(CmdHelp):
def func(self):
if (is_in_combat(self.caller) and (not self.args)):
self.caller.msg(((('Available combat commands:|/' + '|wAttack:|n Attack a target, attempting to deal damage.|/') + '|wPass:|n Pass your turn without further action.|/') + '|wDisengage:|n End your tu... |
def read_tables(config, c=None):
table_reader = build_reader(data_format=config['file_format'], basepath=config['data_dir'], split_row_groups=config['split_row_groups'], backend=config['backend'])
store_sales_df = table_reader.read('store_sales', relevant_cols=store_sales_cols)
date_dim_df = table_reader.re... |
def test_1epoch_fuse(class_limit=None, n_snip=5, opt_flow_len=10, saved_model=None, saved_spatial_weights=None, saved_temporal_weights=None, image_shape=(224, 224), original_image_shape=(341, 256), batch_size=128, fuse_method='average'):
print('class_limit = ', class_limit)
data = DataSet(class_limit=class_limi... |
def submit(modelpath, savepath):
bs = 1
model = UNet(2, 3, opt.start_channel).cuda()
torch.backends.cudnn.benchmark = True
transform = SpatialTransform_1().cuda()
model.load_state_dict(torch.load(modelpath))
model.eval()
transform.eval()
Dices_35 = []
use_cuda = True
device = tor... |
.parametrize('uri', [rfc3986.uri_reference(' rfc3986.uri_reference('/path/to/resource')])
def test_missing_host_component(uri):
validators.Validator().validate(uri)
validator = validators.Validator().require_presence_of('host')
with pytest.raises(exceptions.MissingComponentError):
validator.validate... |
def _detectFoamDir():
foam_dir = None
if (platform.system() == 'Linux'):
cmdline = ['bash', '-i', '-c', 'echo $WM_PROJECT_DIR']
foam_dir = subprocess.check_output(cmdline, stderr=subprocess.PIPE)
if (platform.system() == 'Windows'):
foam_dir = _runCommandOnWSL('echo $WM_PROJECT_DIR')... |
class connecting(controlbase):
def __init__(self, lcd):
super(connecting, self).__init__(lcd)
self.connecting_dots = 0
def display(self, refresh):
if refresh:
self.box(rectangle(0, 0, 1, 0.4), black)
self.fittext(rectangle(0, 0, 1, 0.4), _('connect to server'), Tr... |
class SuperExpr(Expression):
__slots__ = ('name', 'info', 'call')
__match_args__ = ('name', 'call', 'info')
name: str
info: (TypeInfo | None)
call: CallExpr
def __init__(self, name: str, call: CallExpr) -> None:
super().__init__()
self.name = name
self.call = call
... |
def test_download_periodic_stop_at_first_usable(tmp_path, mocker, time_freeze):
time_freeze(_UP_NOW)
wheel = get_embed_wheel('pip', '3.9')
app_data_outer = AppDataDiskFolder(str((tmp_path / 'app')))
pip_version_remote = [wheel_path(wheel, (0, 1, 1)), wheel_path(wheel, (0, 1, 0))]
rel_date_remote = [... |
def random_interaction_operator(n_orbitals, expand_spin=False, real=True, seed=None):
if (seed is not None):
numpy.random.seed(seed)
if real:
dtype = float
else:
dtype = complex
constant = numpy.random.randn()
one_body_coefficients = random_hermitian_matrix(n_orbitals, real)
... |
class QueueWrapper(NonBlocking):
def __init__(self, protocol, response_wait_time=1e-05):
if (not isinstance(protocol, communication.protocol.IterDataPipeQueueProtocolClient)):
raise Exception('Got', protocol)
self.protocol = protocol
self.counter = 0
self._stop_iteration ... |
class CertificateErrorWrapper(usertypes.AbstractCertificateErrorWrapper):
def __init__(self, error: QWebEngineCertificateError) -> None:
super().__init__()
self._error = error
self.ignore = False
def __str__(self) -> str:
if machinery.IS_QT5:
return self._error.errorD... |
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, use_cbam=False):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
... |
def compute_wer(ref_uid_to_tra, hyp_uid_to_tra, g2p, g2p_dict):
d_cnt = 0
w_cnt = 0
w_cnt_h = 0
for uid in hyp_uid_to_tra:
ref = ref_uid_to_tra[uid].split()
if (g2p_dict is not None):
hyp = []
for word in hyp_uid_to_tra[uid].split():
if (word in g2... |
.parametrize('dist_params, obs', [((np.array([0, 0, 0, 0], dtype=np.float64),), np.array([0, 0.5, 1, (- 1)], dtype=np.float64)), ((np.array(0, dtype=np.int64),), np.array(0, dtype=np.int64))])
def test_dirac_delta_logprob(dist_params, obs):
(dist_params_at, obs_at, _) = create_pytensor_params(dist_params, obs, ())
... |
def main():
logger.info('Launching the SAN')
start_test = False
dev_name = 'dev'
opt = vars(args)
logger.info('Loading data')
(embedding, opt) = load_meta(opt, os.path.join(args.multitask_data_path, args.meta))
gold_data = load_gold(args.dev_datasets, args.data_dir, dev_name=dev_name)
(b... |
_on_failure
.parametrize('number_of_nodes', [1])
.parametrize('channels_per_node', [0])
.parametrize('enable_rest_api', [True])
def test_api_get_channel_list(api_server_test_instance: APIServer, token_addresses, reveal_timeout):
partner_address = '0x61C808D82A3AcdaDc13c777b59310bD9'
request = grequests.get(api_... |
class WeightedClassSplitter_(Splitter):
def __init__(self, shuffle=True, min_num_samples=1, max_num_samples=None, weights=None, train_weights=None, test_weights=None, support_weights=None, query_weights=None, force_equal_per_class=False, random_state_seed=0):
self.shuffle = shuffle
self.force_equal_... |
class TestPrometheusMetrics():
def setup(self):
REQUEST_LATENCY.clear()
REQUESTS_TOTAL.clear()
ACTIVE_REQUESTS.clear()
.parametrize('exc,exc_type,status,status_code,expectation', [(None, '', '', '', does_not_raise()), (TApplicationException(TApplicationException.UNKNOWN_METHOD, 'unknown ... |
class SolverResult():
def __init__(self, root: ProjectPackage, packages: list[Package], attempted_solutions: int) -> None:
self._root = root
self._packages = packages
self._attempted_solutions = attempted_solutions
def packages(self) -> list[Package]:
return self._packages
de... |
def test_custom_init_unknown_params():
assert (get_attrs_shape(CustomInitUnknownParams) == Shape(input=InputShape(constructor=CustomInitUnknownParams, kwargs=None, fields=(InputField(type=int, id='a', default=NoDefault(), is_required=True, metadata=MappingProxyType({}), original=ANY), InputField(type=str, id='b', d... |
class HContainer(SplitContainer):
def __init__(self, area):
SplitContainer.__init__(self, area, QtCore.Qt.Orientation.Horizontal)
def type(self):
return 'horizontal'
def updateStretch(self):
x = 0
y = 0
sizes = []
for i in range(self.count()):
(wx,... |
def update_winnowed_channels(original_mask: List[int], new_mask: List[int]):
assert (len(new_mask) == sum(original_mask))
original_mask_ones_indices = get_one_positions_in_binary_mask(original_mask)
new_mask_zero_indices = get_zero_positions_in_binary_mask(new_mask)
for idx in new_mask_zero_indices:
... |
def create_fscommands(root):
dirlist = os.listdir(root)
commands = {'.hg': MercurialCommands, '.svn': SubversionCommands, '.git': GITCommands, '_svn': SubversionCommands, '_darcs': DarcsCommands}
for key in commands:
if (key in dirlist):
try:
return commands[key](root)
... |
_bpe('hf_byte_bpe', dataclass=HuggingFaceByteLevelBPEConfig)
class HuggingFaceByteLevelBPE(object):
def __init__(self, cfg):
try:
from tokenizers import ByteLevelBPETokenizer
except ImportError:
raise ImportError('Please install huggingface/tokenizers with: pip install tokeni... |
class AstViewer(ida_graph.GraphViewer):
def __init__(self, title: str, ast: TritonAst):
ida_graph.GraphViewer.__init__(self, title)
self._ast = ast
def OnRefresh(self) -> bool:
self.Clear()
self.draw()
return True
def OnGetText(self, ida_node_id: int) -> str:
... |
class QuestionSetQuestionSetValidator(InstanceValidator):
def __call__(self, data, serializer=None):
super().__call__(data, serializer)
questionsets = data.get('questionsets')
if (not questionsets):
return
if ((not self.serializer) and (not self.instance)):
re... |
class TestRandomAccessIntReader(_TestRandomAccessReaders, unittest.TestCase, IntExampleMixin):
def checkRead(self, reader):
self.assertEqual(1, reader['one'])
self.assertEqual(3, reader['three'])
self.assertEqual(2, reader['two'])
with self.assertRaises(KeyError):
reader[... |
class SDR_LIKE_Loss(Unfolding_Loss):
def __init__(self, window_length, hop_length, **kwargs):
super().__init__(window_length, hop_length)
def criterion(self, target_signal_hat, target_signal):
s_target = ((((target_signal_hat * target_signal).sum((- 1), keepdims=True) + 1e-08) / ((target_signal ... |
def main():
model = Net_binary().to(device)
optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)
for epoch in range(1, (args.epochs + 1)):
train(args, model, device, train_loader, optimizer, epoch)
print('')
eval_train(model, device, train_loader)
eva... |
class InvertedDoublePendulumEnv(mujoco_env.MujocoEnv, utils.EzPickle):
def __init__(self):
mujoco_env.MujocoEnv.__init__(self, 'inverted_double_pendulum.xml', 5)
utils.EzPickle.__init__(self)
def _step(self, action):
self.do_simulation(action, self.frame_skip)
ob = self._get_obs(... |
def efa_to_devicemounts(num_devices: int) -> List[DeviceMount]:
device_mounts = []
for device_index in range(0, num_devices):
device_mounts.append(DeviceMount(src_path=('/dev/infiniband/uverbs' + str(device_index)), dst_path=('/dev/infiniband/uverbs' + str(device_index))))
return device_mounts |
class InvalidRangeIndexChecker(BaseChecker):
name = 'invalid_range_index'
msgs = {'E9993': ('You should not use invalid range index on line %s', 'invalid-range-index', 'Used when you use invalid index range')}
_required_for_messages('invalid-range-index')
def visit_call(self, node: nodes.Call) -> None:
... |
(context_settings=dict(ignore_unknown_options=True), cls=cli_tools.DocumentedCommand, section=doc.UNSECTIONED)
('pip_args', nargs=(- 1), type=click.UNPROCESSED)
_context
def pip(ctx, pip_args):
cli_args = ([sys.executable, '-m', 'pip'] + list(pip_args))
ctx.exit(subprocess.run(cli_args, check=False).returncode) |
def main():
data_path = './Data/GasPrice.csv'
P = 12
step = 1
(X_train, Y_train, X_test, Y_test, data_df_combined_clean) = load_data(data_path, P=P, step=step)
print(X_train.shape)
print(Y_train.shape)
model = Wavelet_LSTM(P, 32, 1)
model = model.double()
train(model, X_train, Y_trai... |
def test_purview(s):
mechanisms = powerset(s.node_indices)
purviews = powerset(s.node_indices)
for (mechanism, purview) in zip(mechanisms, purviews):
repertoire = s.cause_repertoire(mechanism, purview)
assert (distribution.purview(repertoire) == purview)
assert (distribution.purview(None... |
class MaskedBasicblock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, args=None):
super(MaskedBasicblock, self).__init__()
self.conv_a = nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn_a = nn.BatchNorm2d(... |
def _generate_reference(source: Path, destination: Path, ext: str):
nav_items: Dict[(str, List[str])] = {'Code Reference': []}
for (module_name, aliases) in _parse_package(source):
for alias in aliases:
_write_ref_content((destination / f'{module_name}.{ext}'), module_name, alias.name)
... |
def test_find_extra_reqs(tmp_path: Path) -> None:
installed_not_imported_required_package = pytest
installed_imported_required_package = pip
fake_requirements_file = (tmp_path / 'requirements.txt')
fake_requirements_file.write_text(textwrap.dedent(f''' not_installed_package_12345==1
... |
class TestComposite(TestNameCheckVisitorBase):
_passes()
def test_assignment(self):
class Capybara(object):
def __init__(self, x):
self.x = x
def eat(self):
assert_is_value(self.x, MultiValuedValue([AnyValue(AnySource.unannotated), KnownValue(1)]))... |
class ModelConfigs(BaseModelConfigs):
def __init__(self):
super().__init__()
self.model_path = os.path.join('Models/04_sentence_recognition', datetime.strftime(datetime.now(), '%Y%m%d%H%M'))
self.vocab = ''
self.height = 96
self.width = 1408
self.max_text_length = 0
... |
.supported(only_if=(lambda backend: backend.x448_supported()), skip_message='Requires OpenSSL with X448 support')
def test_public_key_equality(backend):
key_bytes = load_vectors_from_file(os.path.join('asymmetric', 'X448', 'x448-pkcs8.der'), (lambda derfile: derfile.read()), mode='rb')
key1 = serialization.load... |
def test_include_parser():
text = '\n//======//\n// X86 Instruction Format Definitions.\n//\n\ninclude "X86InstrFormats.td"\n\ninclude "X86InstrExtension.td"\n\ninclude "llvm/Target/Target.td"\n\n//======//\n// Pattern fragments.\n//\n\n// X86 specific condition code. These correspond to CondCode in\n// X86InstrInf... |
def SaveGameObjects(gameObjects, data, project):
for gameObject in gameObjects:
attrs = {'name': gameObject.name, 'tag': gameObject.tag.tag, 'enabled': gameObject.enabled, 'transform': ObjectInfo.SkipConv(project.GetUuid(gameObject.transform))}
data.append(ObjectInfo('GameObject', project.GetUuid(ga... |
(hookwrapper=True, trylast=True)
def pytest_runtest_call(item):
with timeout_for_setup_and_call(item):
outcome = (yield)
did_fail = (isinstance(outcome._excinfo, tuple) and isinstance(outcome._excinfo[1], BaseException))
is_xdist = ('PYTEST_XDIST_WORKER' in os.environ)
is_flaky_test ... |
class DockLockDetailsTab(BaseConnectionDetailsTab):
def tab_title(self) -> str:
return 'Door Locks'
def should_appear_for(cls, configuration: BaseConfiguration, all_patches: dict[(int, GamePatches)], players: PlayersConfiguration) -> bool:
return configuration.dock_rando.is_enabled()
def _fi... |
def build_request(endian):
fc = open('genrequest.c', 'w')
fc.write(C_HEADER)
reqlist = list(request.major_codes.items())
reqlist.sort(key=(lambda x: x[0]))
genfuncs = []
req_args = {}
reply_args = {}
for (code, req) in reqlist:
name = req.__name__
creqname = name
... |
def send_contract_view(ModelAdmin, request, pk):
contract = get_object_or_404(ModelAdmin.get_queryset(request), pk=pk)
if ((request.method.upper() == 'POST') and (request.POST.get('confirm') == 'yes')):
use_case = use_cases.SendContractUseCase.build()
try:
use_case.execute(contract, ... |
class Speech2Text2Processor(ProcessorMixin):
feature_extractor_class = 'AutoFeatureExtractor'
tokenizer_class = 'Speech2Text2Tokenizer'
def __init__(self, feature_extractor, tokenizer):
super().__init__(feature_extractor, tokenizer)
self.current_processor = self.feature_extractor
sel... |
def compute_dense_reward(self, action, obs) -> float:
distance_weight = 1.0
goal_weight = 1.0
action_weight = 0.01
grip_to_handle_dist = np.linalg.norm((self.robot.ee_position - self.obj1.position))
handle_to_goal_dist = np.linalg.norm((self.obj1.position - self.goal_position))
action_regulariza... |
def test_send_chat_failed(settings, requests_mock):
settings.PLAIN_API = '
requests_mock.post(settings.PLAIN_API, json={'data': {'upsertCustomTimelineEntry': {'result': 'NOOP', 'timelineEntry': None, 'error': {'message': 'There was a validation error.', 'type': 'VALIDATION', 'code': 'input_validation', 'fields'... |
def arg_options():
short = 'hi:o:amv:'
long = ['ifile=', 'ofile=', 'crepe=', 'crepe_step_size=', 'whisper=', 'whisper_align_model=', 'whisper_batch_size=', 'whisper_compute_type=', 'language=', 'plot=', 'midi=', 'hyphenation=', 'disable_separation=', 'disable_karaoke=', 'create_audio_chunks=', 'force_cpu=', 'fo... |
def validate_keys(dict_, expected, funcname):
expected = set(expected)
received = set(dict_)
missing = (expected - received)
if missing:
raise ValueError('Missing keys in {}:\nExpected Keys: {}\nReceived Keys: {}'.format(funcname, sorted(expected), sorted(received)))
unexpected = (received -... |
_torch
class DecisionTransformerModelIntegrationTest(unittest.TestCase):
def test_autoregressive_prediction(self):
NUM_STEPS = 2
TARGET_RETURN = 10
model = DecisionTransformerModel.from_pretrained('edbeeching/decision-transformer-gym-hopper-expert')
model = model.to(torch_device)
... |
class SingleStageNetwork(nn.Module):
def __init__(self, has_skip=False, gen_skip=False, gen_cross_conv=False, unit_channels=256, num_units=4, num_blocks=[2, 2, 2, 2], norm_cfg=dict(type='BN'), in_channels=64):
norm_cfg = cp.deepcopy(norm_cfg)
num_blocks = cp.deepcopy(num_blocks)
super().__in... |
def restart_and_wait_for_server(nursery: Nursery, port_generator: Iterator[Port], node: RunningNode, retry_timeout: int) -> Optional[RunningNode]:
node.process.send_signal(signal.SIGINT)
exit_code = node.process.result.get()
if (exit_code != 0):
raise Exception(f'Node did not shut down cleanly {node... |
class Server(ServerModule):
def __init__(self, args):
super(Server, self).__init__(args, Client)
self.c2s_sum = []
self.c2s_sig = []
self.c2s_psi = []
self.s2c_sum = []
self.s2c_sig = []
self.s2c_psi = []
self.s2c_hlp = []
self.restored_clients... |
.parametrize('inline_views', (False, True))
def test_deterministics(inline_views):
with pm.Model() as m:
x = pm.Normal('x')
mu = pm.Deterministic('mu', pm.math.abs(x))
sigma = pm.math.exp(x)
pm.Deterministic('sigma', sigma)
y = pm.Normal('y', mu, sigma)
y_ = pm.Determ... |
class PreActResNet(nn.Module):
def __init__(self, block, num_blocks, num_classes=10, deconv=None, delinear=None, channel_deconv=None):
super(PreActResNet, self).__init__()
self.in_planes = 64
if (deconv is None):
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, b... |
def test_raiden_defaults(cli_runner, tmp_path):
datadir = (tmp_path / '.raiden')
datadir.mkdir(parents=True, exist_ok=True)
config_file = (datadir / 'config.toml')
config_file.touch()
expected_defaults = {'datadir': str(datadir), 'config_file': str(config_file), 'chain_id': 1, 'environment_type': En... |
def parse():
parser = argparse.ArgumentParser()
parser.add_argument('--num_init', type=int, help='(int) number of initial points', default=10)
parser.add_argument('--num_total', type=int, default=1000000)
parser.add_argument('--data_loc', type=str, default='../../datasets/malaria_df.hdf5')
parser.ad... |
class ExpiredCopyrightLicense(PublicDomainLicense):
def __init__(self, author_death_year: int):
self.author_death_year = author_death_year
def __repr__(self) -> str:
years_since_author_death = str((datetime.now().year - self.author_death_year))
return f'This image is in the public domain... |
def parse_specifier_for_install(package_spec: str, pip_args: List[str]) -> Tuple[(str, List[str])]:
parsed_package = _parse_specifier(package_spec)
package_or_url = _parsed_package_to_package_or_url(parsed_package, remove_version_specifiers=False)
if (('--editable' in pip_args) and (not parsed_package.valid... |
def approximate_normalized_graph_laplacian(A, rank, which='LA'):
n = A.shape[0]
(L, d_rt) = csgraph.laplacian(A, normed=True, return_diag=True)
X = (sparse.identity(n) - L)
logger.info('Eigen decomposition...')
(evals, evecs) = sparse.linalg.eigsh(X, rank, which=which)
logger.info('Maximum eigen... |
class SharedMemoryRingBuffer():
def __init__(self, shm_manager: SharedMemoryManager, array_specs: List[ArraySpec], get_max_k: int, get_time_budget: float, put_desired_frequency: float, safety_margin: float=1.5):
counter = SharedAtomicCounter(shm_manager)
buffer_size = (int(np.ceil(((put_desired_freq... |
def main():
parser = argparse.ArgumentParser(description='PyTorch Siamese network Example')
parser.add_argument('--batch-size', type=int, default=64, metavar='N', help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N', help='input bat... |
.parametrize('dt', [None, 0, 0.1])
def test_composition_override(dt):
(A, B, C, D) = ([[1, 1], [0, 1]], [[0], [1]], [[1, 0]], 0)
sys1 = ct.ss(A, B, C, D, None, inputs='u1', outputs='y1')
sys2 = ct.ss(A, B, C, D, None, inputs='y1', outputs='y2')
sys3 = ct.interconnect([sys1, sys2], inputs='u1', outputs='... |
def test_restart_hook_and_state(manager_nospawn, request, backend, backend_name):
if (backend_name == 'wayland'):
pytest.skip('Skipping test on Wayland.')
manager = manager_nospawn
inject = textwrap.dedent('\n from libqtile.core.lifecycle import lifecycle\n\n def no_op(*args, **kwargs)... |
def extension_file(module, canary):
if (ENABLE_SUPPORT_DETECTION and (not hasattr(GSSAPI_LIB, canary))):
print(('Skipping the %s extension because it is not supported by your GSSAPI implementation...' % module))
return
try:
ENUM_EXTS.append(make_extension('gssapi.raw._enum_extensions.ext... |
class MetricLogger(object):
def __init__(self, delimiter='\t'):
self.meters = defaultdict(SmoothedValue)
self.delimiter = delimiter
def update(self, **kwargs):
for (k, v) in kwargs.items():
if isinstance(v, torch.Tensor):
v = v.item()
assert isinst... |
class FuncItem(FuncBase):
__slots__ = ('arguments', 'arg_names', 'arg_kinds', 'min_args', 'max_pos', 'body', 'is_overload', 'is_generator', 'is_coroutine', 'is_async_generator', 'is_awaitable_coroutine', 'expanded')
__deletable__ = ('arguments', 'max_pos', 'min_args')
def __init__(self, arguments: (list[Arg... |
def test_make_reservation(test_session, room_display):
room = test_session.query(Room).first()
new_reservation = Reservation.make(room=room, date_in=datetime.datetime(2023, 4, 1), date_out=datetime.datetime(2023, 4, 2), guest=Guest(mobile='+82-10-1111-2222', name='Guido'))
test_session.add(new_reservation)
... |
def test_custom_locale_selector():
app = flask.Flask(__name__)
b = babel.Babel(app)
d = datetime(2010, 4, 12, 13, 46)
the_timezone = 'UTC'
the_locale = 'en_US'
def select_locale():
return the_locale
def select_timezone():
return the_timezone
get_babel(app).locale_selector... |
def general_ict_model_provider(only_query_model=False, only_block_model=False):
args = get_args()
assert (args.ict_head_size is not None), 'Need to specify --ict-head-size to provide an ICTBertModel'
assert (args.model_parallel_size == 1), 'Model parallel size > 1 not supported for ICT'
print_rank_0('bu... |
.parametrize('template', ['{}', 'attachment; filename="{}"', 'inline; {}', 'attachment; {}="foo"', "attachment; filename*=iso-8859-1''{}", 'attachment; filename*={}'])
(strategies.text(alphabet=[chr(x) for x in range(255)]))
def test_parse_content_disposition_hypothesis(caplog, template, stubs, s):
header = templat... |
def main():
args = get_args()
try:
run(args)
except:
logger.error('Failed to resolve overlaps', exc_info=True)
raise SystemExit(1)
finally:
try:
for f in [args.segments, args.ctm_in, args.ctm_out]:
if (f is not None):
f.clos... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.