code stringlengths 281 23.7M |
|---|
def valid(args, train_env, val_envs, rank=(- 1)):
default_gpu = is_default_gpu(args)
agent_class = SoonGMapObjectNavAgent
agent = agent_class(args, train_env, rank=rank)
if (args.resume_file is not None):
print(('Loaded the listener model at iter %d from %s\n' % (agent.load(args.resume_file), ar... |
class Effect5570(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
for attrName in ('buffDuration', 'warfareBuff1Value', 'warfareBuff2Value', 'warfareBuff3Value', 'warfareBuff4Value'):
fit.modules.filteredItemBoost((lambda mod: (mod.item.requiresSkill('... |
class TANMedia5(DataElementGroup):
tan_medium_class = CodeField(enum=TANMediaClass4, _d='TAN-Medium-Klasse')
status = CodeField(enum=TANMediumStatus, _d='Status')
security_function = DataElementField(type='num', required=False, _d='Sicherheitsfunktion, kodiert')
card_number = DataElementField(type='id',... |
class BasicBlock(nn.Module):
def __init__(self, in_chan, out_chan, stride=1):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(in_chan, out_chan, stride)
self.bn1 = nn.BatchNorm2d(out_chan)
self.conv2 = conv3x3(out_chan, out_chan)
self.bn2 = nn.BatchNorm2d(out_chan)
... |
def get_rmm_device_memory_usage() -> Optional[int]:
def get_rmm_memory_resource_stack(mr) -> list:
if hasattr(mr, 'upstream_mr'):
return ([mr] + get_rmm_memory_resource_stack(mr.upstream_mr))
return [mr]
try:
import rmm
except ImportError:
return None
for mr i... |
def __compute_folding_ranges(tree, lines):
folding_ranges = {}
stack = [tree]
while (len(stack) > 0):
node = stack.pop(0)
if isinstance(node, tree_nodes.Newline):
continue
if isinstance(node, tree_nodes.PythonErrorNode):
(start_line, _) = node.start_pos
... |
class ByT5TokenizationTest(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = ByT5Tokenizer
test_rust_tokenizer = False
def setUp(self):
super().setUp()
tokenizer = ByT5Tokenizer()
tokenizer.save_pretrained(self.tmpdirname)
_property
def t5_base_tokenizer(self):
... |
.unit()
.parametrize(('func', 'name', 'expectation', 'expected'), [(task_func, None, does_not_raise(), 'task_func'), (task_func, 'name', does_not_raise(), 'name'), (partial(task_func, x=1), None, does_not_raise(), 'task_func'), (partial(task_func, x=1), 'name', does_not_raise(), 'name'), ((lambda x: None), None, does_n... |
def parser_options():
parser = argparse.ArgumentParser()
parser.add_argument('--path_opt', default='option/SYDNEY_GaLR.yaml', type=str, help='path to a yaml options file')
opt = parser.parse_args()
with open(opt.path_opt, 'r') as handle:
options = yaml.safe_load(handle)
return options |
def get_test_data(n1, offset, n2):
ih = intelhex.IntelHex()
addr = 0
for i in range_g(n1):
ih[addr] = (addr % 256)
addr += 1
addr += offset
for i in range_g(n2):
ih[addr] = (addr % 256)
addr += 1
sio = StringIO()
ih.write_hex_file(sio)
hexstr = sio.getvalu... |
def test_singlediode_series(cec_module_params):
times = pd.date_range(start='2015-01-01', periods=2, freq='12H')
effective_irradiance = pd.Series([0.0, 800.0], index=times)
(IL, I0, Rs, Rsh, nNsVth) = pvsystem.calcparams_desoto(effective_irradiance, temp_cell=25, alpha_sc=cec_module_params['alpha_sc'], a_re... |
def main():
st.set_page_config(initial_sidebar_state='expanded', page_title='BabyAGI UI', layout='centered')
with st.sidebar:
openai_api_key = st.text_input('Your OpenAI API KEY', type='password')
model_name = st.selectbox('Model name', options=['gpt-3.5-turbo', 'gpt-4', 'text-davinci-003'])
... |
class SponsorshipModelTests(TestCase):
def setUp(self):
self.benefits = baker.make(SponsorshipBenefit, _quantity=5, _fill_optional=True)
self.package = baker.make('sponsors.SponsorshipPackage', name='PSF Sponsorship Program', sponsorship_amount=100)
self.package.benefits.add(*self.benefits)
... |
class UNetDecoder(nn.Module):
def __init__(self, encoder: Union[(PlainConvEncoder, ResidualEncoder)], num_classes: int, n_conv_per_stage: Union[(int, Tuple[(int, ...)], List[int])], deep_supervision, nonlin_first: bool=False):
super().__init__()
self.deep_supervision = deep_supervision
self.... |
class TestKeyedJaggedTensorScripting(unittest.TestCase):
def test_scriptable_forward(self) -> None:
class MyModule(torch.nn.Module):
def forward(self, input: KeyedJaggedTensor) -> KeyedJaggedTensor:
input['any'].values()
input.dist_labels()
input.d... |
def perf_attrib(returns, positions, factor_returns, factor_loadings):
start = returns.index[0]
end = returns.index[(- 1)]
factor_returns = factor_returns.loc[start:end]
factor_loadings = factor_loadings.loc[start:end]
factor_loadings.index = factor_loadings.index.set_names(['dt', 'ticker'])
posi... |
def test_history_edit(monkeypatch):
app = cmd2.Cmd(multiline_commands=['alias'])
app.editor = 'fooedit'
edit_mock = mock.MagicMock(name='run_editor')
monkeypatch.setattr('cmd2.Cmd.run_editor', edit_mock)
run_script_mock = mock.MagicMock(name='do_run_script')
monkeypatch.setattr('cmd2.Cmd.do_run_... |
def test_illegal_inport_deep_write():
class B(ComponentLevel3):
def construct(s):
s.in_ = InPort(Bits32)
def up_B_print():
print(s.in_)
class BWrap(ComponentLevel3):
def construct(s):
s.b = B()
class Top(ComponentLevel3):
def constr... |
class RK23(RKAdaptiveStepSolver):
error_estimator_order = 2
n_stages = 3
C = torch.tensor([0, (1 / 2), (3 / 4)], dtype=torch.float64)
A = torch.tensor([[0, 0, 0], [(1 / 2), 0, 0], [0, (3 / 4), 0]], dtype=torch.float64)
B = torch.tensor([(2 / 9), (1 / 3), (4 / 9)], dtype=torch.float64)
E = torch.... |
def run_training_entry():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('dataset_name_or_id', type=str, help='Dataset name or ID to train with')
parser.add_argument('configuration', type=str, help='Configuration that should be trained')
parser.add_argument('fold', type=str, ... |
.parametrize('op, x, exc, op_args', [(nlinalg.MatrixInverse, set_test_value(pt.dmatrix(), (lambda x: x.T.dot(x))(rng.random(size=(3, 3)).astype('float64'))), None, ()), (nlinalg.MatrixInverse, set_test_value(pt.lmatrix(), (lambda x: x.T.dot(x))(rng.integers(1, 10, size=(3, 3)).astype('int64'))), None, ()), (nlinalg.Mat... |
.parametrize('entitytrigger', [OSC.EndOfRoadCondition(2), OSC.CollisionCondition('hej'), OSC.OffroadCondition(3), OSC.TimeHeadwayCondition('my entity', 2, OSC.Rule.greaterOrEqual), OSC.TimeToCollisionCondition(1, OSC.Rule.greaterOrEqual, entity='target'), OSC.AccelerationCondition(2, OSC.Rule.greaterOrEqual), OSC.Stand... |
def model_grads_to_master_grads(model_params, master_params, flat_master=False):
if flat_master:
master_params[0].grad.data.copy_(_flatten_dense_tensors([p.grad.data for p in model_params]))
else:
for (model, master) in zip(model_params, master_params):
if (model.grad is not None):
... |
class StoryViewTests(TestCase):
def setUp(self):
self.user = UserFactory(username='username', password='password')
self.category = StoryCategoryFactory(name='Arts')
self.story1 = StoryFactory(category=self.category, featured=True)
self.story2 = StoryFactory(category=self.category, is... |
def ecp_int(cell, kpts=None):
from pyscf.pbc.df import incore
lib.logger.debug(cell, 'PBC-ECP integrals')
if (kpts is None):
kpts_lst = numpy.zeros((1, 3))
else:
kpts_lst = numpy.reshape(kpts, ((- 1), 3))
(cell, contr_coeff) = gto.cell._split_basis(cell)
lib.logger.debug1(cell, '... |
def parse_args():
parser = argparse.ArgumentParser(description='Build grounding between QDMR and SQL.')
parser.add_argument('--output_path', type=str, default=None, help='path to output file with grounding (found correct SPARQL script)')
parser.add_argument('--output_path_all', type=str, default=None, help=... |
_torch_tpu
class TorchXLAExamplesTests(TestCasePlus):
def test_run_glue(self):
import xla_spawn
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f'''
./examples/pytorch/text-classification/run_glue.py
--num_cores=8
./examples/pytorch/text-classification... |
class Ssverification(Cog):
def __init__(self, bot: Quotient):
self.bot = bot
self.request_url = (self.bot.config.FASTAPI_URL + '/ocr')
self.headers = {'authorization': self.bot.config.FASTAPI_KEY, 'Content-Type': 'application/json'}
self.__mratelimiter = MemberLimits(QuotientRatelimi... |
def address_to_script(addr: str, *, net=None) -> str:
if (net is None):
net = constants.net
if (not is_address(addr, net=net)):
raise BitcoinException(f'invalid Qtum address: {addr}')
(witver, witprog) = segwit_addr.decode(net.SEGWIT_HRP, addr)
if (witprog is not None):
if (not (... |
def test_cli_async_map(runner, reactor, server, capsys):
base_url = '
in_stream = ''.join((base_url.format(i) for i in [1, 1, 5, 1]))
args = ['--exec-before', 'import datetime; now=datetime.datetime.now; START_TIME=now()', 'async-map', 'await asks.get ! f"{types.SimpleNamespace(**x.json()).delay}"']
ex... |
class AnimatedToggle(Toggle):
_transparent_pen = QPen(Qt.transparent)
_light_grey_pen = QPen(Qt.lightGray)
def __init__(self, *args, pulse_unchecked_color='#', pulse_checked_color='#4400B0EE', **kwargs):
self._pulse_radius = 0
super().__init__(*args, **kwargs)
self.animation = QPrope... |
def interpret_dc_type(field_type):
if isinstance(field_type, str):
raise RuntimeError('field should be a type')
if (field_type == Any):
return str
typestring = str(field_type)
if (re.match('(typing.|^)Union\\[(.*), NoneType\\]$', typestring) or typestring.startswith('typing.Optional')):
... |
def user_view(user, password=None):
user_data = {'kind': 'user', 'name': user.username, 'username': user.username, 'email': user.email, 'verified': user.verified, 'avatar': avatar.get_data_for_user(user), 'super_user': usermanager.is_superuser(user.username), 'enabled': user.enabled}
if (password is not None):
... |
def convert_raw_tx_to_hex(raw: Union[(str, bytes)]) -> str:
if (not raw):
raise ValueError('empty string')
raw_unstripped = raw
raw = raw.strip()
try:
return binascii.unhexlify(raw).hex()
except:
pass
try:
return base_decode(raw, base=43).hex()
except:
... |
class JobDetail(JobMixin, DetailView):
def get_queryset(self):
queryset = Job.objects.select_related()
if self.has_jobs_board_admin_access():
return queryset
if self.request.user.is_authenticated:
return (queryset.visible() | queryset.by(self.request.user))
re... |
def mlp(dim, hidden_dim, output_dim, layers=1, batch_norm=False):
if batch_norm:
seq = [nn.Linear(dim, hidden_dim), nn.BatchNorm1d(num_features=hidden_dim), nn.ReLU(inplace=True)]
for _ in range(layers):
seq += [nn.Linear(hidden_dim, hidden_dim), nn.BatchNorm1d(num_features=hidden_dim), ... |
.skipif((sys.implementation.name != 'cpython'), reason='Only makes sense with refcounting GC')
def test_ExceptionGroup_catch_doesnt_create_cyclic_garbage() -> None:
gc.collect()
old_flags = gc.get_debug()
def make_multi() -> NoReturn:
raise ExceptionGroup('', [get_exc(raiser1), get_exc(raiser2)])
... |
class DamagePattern():
instance = None
def getInstance(cls):
if (cls.instance is None):
cls.instance = DamagePattern()
return cls.instance
def getUserDamagePatternList():
return eos.db.getDamagePatternList()
def getBuiltinDamagePatternList():
return es_DamageP... |
def schedule_threshold(step: int, total_step: int, warmup_steps: int, initial_threshold: float, final_threshold: float, initial_warmup: int, final_warmup: int, final_lambda: float):
if (step <= (initial_warmup * warmup_steps)):
threshold = initial_threshold
elif (step > (total_step - (final_warmup * war... |
def _create_gda(partitioner: partitioning.BasePartitioner, global_shapes: PyTreeDef, host_arrays: PyTreeDef) -> PyTreeDef:
global_mesh = partitioner.mesh
axes = partitioner.data_partition_spec
local_devices = global_mesh.local_devices
local_device_count = jax.local_device_count()
def _put_to_devices... |
class HookContainer():
def __init__(self, record_keeper, record_group_name_prefix=None, primary_metric='mean_average_precision_at_r', validation_split_name='val', save_models=True):
self.record_keeper = record_keeper
self.record_group_name_prefix = record_group_name_prefix
self.saveable_trai... |
.parametrize('message', ['Undefined name `os`', "F821 undefined name 'numpy'", "undefined name 'numpy'"])
def test_autoimport_code_actions_get_correct_module_name(autoimport_workspace, message):
source = "os.path.join('a', 'b')"
autoimport_workspace.put_document(DOC_URI, source=source)
doc = autoimport_work... |
def get_date_diff_display(start, end):
if (end.year != start.year):
return f"{start.strftime('%d %b %Y')} - {end.strftime('%d %b %Y')}"
if (end.month != start.month):
return f"{start.strftime('%d %b')} - {end.strftime('%d %b')}, {start.year}"
if (end.day != start.day):
return f"{star... |
class OptimizedWildRelNet(tf.keras.Model):
def __init__(self, edge_mlp=gin.REQUIRED, graph_mlp=gin.REQUIRED, dropout_in_last_graph_layer=gin.REQUIRED, name='OptimizedWildRelNet', **kwargs):
super(OptimizedWildRelNet, self).__init__(name=name, **kwargs)
edge_layers = []
for num_units in edge_... |
def recursively_load_weights(fairseq_model, hf_model):
unused_weights = []
fairseq_dict = fairseq_model.state_dict()
feature_extractor = hf_model.feature_extractor
for (name, value) in fairseq_dict.items():
is_used = False
if ('conv_layers' in name):
load_conv_layer(name, val... |
def sphash(coords: torch.Tensor, offsets: Optional[torch.Tensor]=None) -> torch.Tensor:
assert (coords.dtype == torch.int), coords.dtype
assert ((coords.ndim == 2) and (coords.shape[1] == 4)), coords.shape
coords = coords.contiguous()
if (offsets is None):
if (coords.device.type == 'cuda'):
... |
def process_rule_environment_table(c, db_id):
c.execute('\nINSERT INTO rule_environment (rule_id, environment_fingerprint_id, radius, num_pairs)\n SELECT rule_map.new_rule_id,\n environment_fingerprint_map.new_environment_fingerprint_id,\n old_rule_environment.radius,\n old_rule_environment... |
class TestLogFilter():
def test_valid(self, parser):
args = parser.parse_args(['--logfilter', 'misc'])
assert (args.logfilter == 'misc')
def test_invalid(self, parser, capsys):
with pytest.raises(SystemExit):
parser.parse_args(['--logfilter', 'invalid'])
(_out, err) =... |
class Rainbow(LedProgram):
def __init__(self, manager: 'DeviceManager') -> None:
super().__init__(manager, 'Rainbow')
self.program_duration = 1
self.time_passed = 0.0
self.current_fraction = 0.0
def start(self) -> None:
self.time_passed = 0.0
def compute(self) -> None... |
('mmseg.datasets.CustomDataset.load_annotations', MagicMock)
('mmseg.datasets.CustomDataset.__getitem__', MagicMock(side_effect=(lambda idx: idx)))
def test_custom_dataset_custom_palette():
dataset = CustomDataset(pipeline=[], img_dir=MagicMock(), split=MagicMock(), classes=('bus', 'car'), palette=[[100, 100, 100],... |
class VoVGSCSP(nn.Module):
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
super().__init__()
c_ = int((c2 * e))
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c1, c_, 1, 1)
self.gsb = GSBottleneck(c_, c_, 1, 1)
self.res = Conv(c_, c_, 3, 1, act=False)
... |
def prepare_env(args, pm, stage, prefix, cmdlist, output=None):
if (args.verbose > 0):
print('{}'.format(prefix))
for cmdinfo in cmdlist:
if isinstance(cmdinfo, list):
exit_codes = cmdinfo[1:]
cmd = cmdinfo[0]
else:
exit_codes = [0]
cmd = c... |
class RaisesContext(ContextManager[_pytest._code.ExceptionInfo[E]]):
def __init__(self, expected_exception: Union[(Type[E], Tuple[(Type[E], ...)])], message: str, match_expr: Optional[Union[(str, Pattern[str])]]=None) -> None:
self.expected_exception = expected_exception
self.message = message
... |
def get_exchanges_by_ccy(history=True):
if (not history):
return dictinvert(CURRENCIES)
d = {}
exchanges = CURRENCIES.keys()
for name in exchanges:
klass = globals()[name]
exchange = klass(None, None)
d[name] = exchange.history_ccys()
return dictinvert(d) |
class SuccessPage(Gtk.Box):
def __init__(self, parent_window):
super().__init__(spacing=10)
self.__parent_window = parent_window
self.grid = Gtk.Grid()
hbox = Gtk.HBox()
previous = Gtk.Button(label=' ')
previous.props.relief = Gtk.ReliefStyle.NONE
previo... |
def unwrap_yielded(yielded: Union[(Block, dict, Iterable)], **kwargs: Any) -> Generator[(dict, None, None)]:
if isinstance(yielded, Block):
(yield dict(iter(yielded)))
elif isinstance(yielded, dict):
(yield yielded)
else:
root = kwargs.get('root', yielded)
parent = kwargs.get... |
class Avd():
_TASKLIST_CMD = ('python', 'a_swapper = {}', 'o_tasks = {}', 'o_pid = {}', "addr = gdb.execute('x/a %d'%(a_swapper + o_tasks), to_string=True).split(':\\t')[1]", 'addr = int(addr, 16) - o_tasks', 'while addr != a_swapper:', " pid = gdb.execute('x/wx %d'%(addr + o_pid), to_string=True).split(':\\t')[1... |
class HFTracer(Tracer):
proxy_buffer_attributes: bool = True
allow_insert_stateless_mods: bool = True
_TORCH_METHODS_TO_PATCH = ['arange', 'zeros', 'ones', 'full', 'full_like', 'eye', 'empty', 'tensor', 'clamp', 'finfo']
def __init__(self, autowrap_modules=(math,), autowrap_functions=()):
super(... |
class TokenManager():
def closeHandle(handle):
try:
CloseHandle(handle)
except Exception as e:
logging.warning('Impossible to close handle {0}: {1}'.format(handle, e))
return False
return True
def getTokenInformationTokenUser(hToken):
infoSize ... |
class MarshallingTest(object):
def test_marshal(self):
model = OrderedDict([('foo', fields.Raw)])
marshal_dict = OrderedDict([('foo', 'bar'), ('bat', 'baz')])
output = marshal(marshal_dict, model)
assert isinstance(output, dict)
assert (not isinstance(output, OrderedDict))
... |
def _test_sharding_from_meta(tables: List[EmbeddingBagConfig], rank: int, world_size: int, sharder: ModuleSharder[nn.Module], backend: str, local_size: Optional[int]=None, use_fp_collection: bool=False) -> None:
with MultiProcessContext(rank, world_size, backend, local_size) as ctx:
(sparse_arch, sharded_sp... |
class PairClassificationPipeline(Pipeline):
def _sanitize_parameters(self, **kwargs):
preprocess_kwargs = {}
if ('second_text' in kwargs):
preprocess_kwargs['second_text'] = kwargs['second_text']
return (preprocess_kwargs, {}, {})
def preprocess(self, text, second_text=None):... |
def _float_to_int(api: CheckerPluginInterface, typ: Type) -> Type:
typ = get_proper_type(typ)
if isinstance(typ, Instance):
if (typ.type.fullname == 'builtins.float'):
return api.named_generic_type('builtins.int', [])
elif typ.args:
return typ.copy_modified(args=[_float_t... |
def test_close(win32rawprinter, caplog, mocker):
PyPrinterHANDLE = mocker.Mock()
PyPrinterHANDLE.return_value = 0
mocker.patch('escpos.printer.Win32Raw.printers', new={'test_printer': 'Test'})
win32rawprinter.printer_name = 'test_printer'
assert (win32rawprinter.printer_name in win32rawprinter.print... |
def check_filter(qdmr_args, i_op, qdmr, change_stage=0):
ok = True
corrected = None
ok = (ok and (len(qdmr_args) == 2))
ok = (ok and QdmrInstance.is_good_qdmr_ref(qdmr_args[0], i_op))
matches = re.findall(BETWEEN_RE_PATTERN, qdmr_args[1], flags=re.IGNORECASE)
if matches:
ok = False
... |
def _get_namedtuple_fields(node: nodes.Call) -> str:
names = []
container = None
try:
container = next(node.args[1].infer())
except (InferenceError, StopIteration) as exc:
raise UseInferenceDefault from exc
except IndexError:
pass
if (not container):
for keyword_n... |
class Scheduler():
def __init__(self, core):
self.pyload = core
self._ = core._
self.queue = PriorityQueue()
def add_job(self, t, call, args=[], kwargs={}, threaded=True):
d = Deferred()
t += time.time()
j = Job(t, call, args, kwargs, d, threaded)
self.que... |
def test_top_down_JHMDB_dataset_compatibility():
dataset = 'TopDownJhmdbDataset'
dataset_class = DATASETS.get(dataset)
dataset_class.load_annotations = MagicMock()
dataset_class.coco = MagicMock()
channel_cfg = dict(num_output_channels=15, dataset_joints=15, dataset_channel=[[0, 1, 2, 3, 4, 5, 6, 7,... |
class AddressBook(Base):
__tablename__ = 'access_address_book'
id = Column(Integer, primary_key=True)
owner_id = Column(Integer, ForeignKey(EmailAndPasswordSystemAccount.id), nullable=False)
owner = relationship(EmailAndPasswordSystemAccount)
collaborators = relationship('reahl.doc.examples.tutorial... |
class PPL():
FFHQ_CROP = [((1 / 8) * 3), ((1 / 8) * 7), ((1 / 8) * 2), ((1 / 8) * 6)]
def __init__(self, G, prior_generator, device=None, num_samples=50000, epsilon=0.0001, use_dlatent=True, full_sampling=False, crop=None, lpips_model=None, lpips_size=None):
device_ids = []
if isinstance(G, torc... |
class TestWithRootDir(TestOSRelease):
def setup_method(self, test_method: FunctionType) -> None:
dist = test_method.__name__.split('_')[1]
root_dir = os.path.join(DISTROS_DIR, dist)
self.distro = distro.LinuxDistribution(include_lsb=False, include_uname=False, include_oslevel=False, os_relea... |
def correct_pad(kernel_size: Union[(int, Tuple)], adjust: bool=True):
if isinstance(kernel_size, int):
kernel_size = (kernel_size, kernel_size)
correct = ((kernel_size[0] // 2), (kernel_size[1] // 2))
if adjust:
return ((correct[1] - 1), correct[1], (correct[0] - 1), correct[0])
else:
... |
class HelpApp(cmd2.Cmd):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def do_squat(self, arg):
pass
def help_squat(self):
self.stdout.write('This command does diddly squat...\n')
def do_edit(self, arg):
pass
def do_undoc(self, arg):
p... |
class LE(LogicalComparison):
identity = False
commutative = False
associative = False
nfunc_spec = ('less_equal', 2, 1)
def impl(self, x, y):
return np.less_equal(x, y)
def c_code(self, node, name, inputs, outputs, sub):
(x, y) = inputs
(z,) = outputs
if (node.inp... |
.parametrize('data_fcn, plot_fcn, mimo', [(control.step_response, control.time_response_plot, True), (control.step_response, control.TimeResponseData.plot, True), (control.frequency_response, control.FrequencyResponseData.plot, True), (control.frequency_response, control.bode, True), (control.frequency_response, contro... |
class DataArguments():
is_blank: Optional[bool] = field(default=False)
image_res: Optional[int] = field(default=512)
img_root_dir: str = field(default='../../PMC-VQA/images/', metadata={'help': 'Path to the training data.'})
Train_csv_path: str = field(default='../../PMC-VQA/train.csv', metadata={'help'... |
def test_SumScaler_no_change_original_dm(decision_matrix):
dm = decision_matrix(seed=42, min_alternatives=10, max_alternatives=10, min_criteria=20, max_criteria=20, min_objectives_proportion=0.5)
expected = dm.copy()
scaler = SumScaler(target='both')
dmt = scaler.transform(dm)
assert (dm.equals(expe... |
class ThresholdReducer(BaseReducer):
def __init__(self, low=None, high=None, **kwargs):
super().__init__(**kwargs)
assert ((low is not None) or (high is not None)), 'At least one of low or high must be specified'
self.low = low
self.high = high
if (self.low is not None):
... |
def read_minimal_logic_db(data: (dict | None)) -> (MinimalLogicData | None):
if (data is None):
return None
return MinimalLogicData(items_to_exclude=[IndexWithReason(it['name'], it.get('when_shuffled')) for it in data['items_to_exclude']], custom_item_amount={it['name']: it['value'] for it in data['cust... |
class DAT(nn.Module):
def __init__(self, img_size=224, patch_size=4, num_classes=1000, expansion=4, dim_stem=96, dims=[96, 192, 384, 768], depths=[2, 2, 18, 2], heads=[3, 6, 12, 24], window_sizes=[7, 7, 7, 7], drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.3, strides=[(- 1), (- 1), 1, 1], offset_range_factor=[... |
class ResNet(nn.Module):
def __init__(self, block=BasicBlock, keep_prob=1.0, avg_pool=False, drop_rate=0.0, dropblock_size=5):
self.inplanes = 3
super(ResNet, self).__init__()
self.layer1 = self._make_layer(block, 64, stride=2, drop_rate=drop_rate)
self.layer2 = self._make_layer(bloc... |
def test_building_scenariooutline_scenarios(mocker):
scenario_outline = ScenarioOutline(1, 'Scenario Outline', 'Examples', 'I am a Scenario Outline', 'foo.feature', 1, parent=None, tags=None, preconditions=None, background=None)
scenario_outline.steps.extend([mocker.MagicMock(sentence='Given I have <foo>', path... |
class OHNMLoss(nn.Module):
def __init__(self, neg_ratio=3.0):
super(OHNMLoss, self).__init__()
self.neg_ratio = neg_ratio
def forward(self, input, target):
pos_logits = input[(target > 0)]
pos_labels = target[(target > 0)]
neg_logits = input[(target == 0)]
neg_lab... |
class TestKernelBWLookup(unittest.TestCase):
def test_uvm_caching_bw(self) -> None:
compute_device: str = 'cuda'
computer_kernel: str = EmbeddingComputeKernel.FUSED_UVM_CACHING.value
caching_ratios: List[float] = [0, 0.25, 0.5, 0.75, 1]
uvm_caching_bw: list[Optional[float]] = [kernel... |
def get_model_test_files():
_ignore_files = ['test_modeling_common', 'test_modeling_encoder_decoder', 'test_modeling_flax_encoder_decoder', 'test_modeling_flax_speech_encoder_decoder', 'test_modeling_marian', 'test_modeling_tf_common', 'test_modeling_tf_encoder_decoder']
test_files = []
for file_or_dir in o... |
class Application(QApplication):
new_window = pyqtSignal(mainwindow.MainWindow)
window_closing = pyqtSignal(mainwindow.MainWindow)
def __init__(self, args):
self._last_focus_object = None
qt_args = qtargs.qt_args(args)
log.init.debug('Commandline args: {}'.format(sys.argv[1:]))
... |
class UserMemoryManager():
def __init__(self, name: str=None, backend: str=LOCAL, memory_pool: Dict=None):
self.backend = backend
self.name = name
if (self.backend == LOCAL):
if (memory_pool is None):
memory_pool = {}
self.memory_pool = memory_pool
... |
class Window(QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.setupModel()
nameLabel = QLabel('Na&me:')
nameEdit = QLineEdit()
addressLabel = QLabel('&Address:')
addressEdit = QTextEdit()
ageLabel = QLabel('A&ge (in years):'... |
def _binst_on_classical_vals(binst: BloqInstance, pred_cxns: Iterable[Connection], soq_assign: Dict[(Soquet, ClassicalValT)]):
for cxn in pred_cxns:
soq_assign[cxn.right] = soq_assign[cxn.left]
def _in_vals(reg: Register):
return _get_in_vals(binst, reg, soq_assign=soq_assign)
bloq = binst.b... |
def ensure_image_locations(*names):
with db_transaction():
locations = ImageStorageLocation.select().where((ImageStorageLocation.name << names))
insert_names = list(names)
for location in locations:
insert_names.remove(location.name)
if (not insert_names):
ret... |
class MaskedConv2d(nn.Conv2d):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True):
super(MaskedConv2d, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias)
def forward(self, input, mask=None):
... |
.filterwarnings('ignore:The input coordinates to pcolor:UserWarning')
def test_anim_spin_distribution():
j = 5
psi = qutip.spin_state(j, (- j))
psi = qutip.spin_coherent(j, (np.random.rand() * np.pi), ((np.random.rand() * 2) * np.pi))
theta = np.linspace(0, np.pi, 50)
phi = np.linspace(0, (2 * np.pi... |
class Effect8048(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Small Vorton Projector')), 'damageMultiplier', ship.getModifiedItemAttr('shipBonusUF2'), skill='EDENCOM Frigate', **kwargs) |
def cut(mol):
if (not mol.HasSubstructMatch(Chem.MolFromSmarts('[*]-;![*]'))):
return None
bis = random.choice(mol.GetSubstructMatches(Chem.MolFromSmarts('[*]-;![*]')))
bs = [mol.GetBondBetweenAtoms(bis[0], bis[1]).GetIdx()]
fragments_mol = Chem.FragmentOnBonds(mol, bs, addDummies=True, dummyLab... |
def _nested_pack(flat_iter, structure):
if is_namedtuple(structure):
return type(structure)(*[_nested_pack(flat_iter, x) for x in structure])
elif isinstance(structure, (list, tuple)):
return type(structure)((_nested_pack(flat_iter, x) for x in structure))
elif isinstance(structure, dict):
... |
class ColorFormatter(logging.Formatter):
color_dic = {'DEBUG': 37, 'INFO': 36, 'WARNING': 33, 'ERROR': 31, 'CRITICAL': 41}
def format(self, record):
color = self.color_dic.get(record.levelname, 37)
record.levelname = '\x1b[{}m{}\x1b[0m'.format(color, record.levelname)
return logging.Form... |
class F27_Network(F25_Network):
removedKeywords = F25_Network.removedKeywords
removedAttrs = F25_Network.removedAttrs
def __init__(self, writePriority=0, *args, **kwargs):
self.bind_to_choices = [BIND_TO_MAC]
F25_Network.__init__(self, writePriority, *args, **kwargs)
def _getParser(self)... |
class TestAddStateIndependentNormalScale():
def test_add_scale_basic(self, num_outputs=4):
module = nn.Linear(3, num_outputs)
module_normal = AddStateIndependentNormalScale(num_outputs)
tensor = torch.randn(3)
(loc, scale) = module_normal(module(tensor))
assert (loc.shape == ... |
(scope='session', autouse=True)
def clean_mask(zarr_dataset: ChunkedDataset) -> Iterator[None]:
agents_mask_path = (Path(zarr_dataset.path) / 'agents_mask')
if agents_mask_path.exists():
rmtree(str(agents_mask_path))
(yield None)
agents_mask_path = (Path(zarr_dataset.path) / 'agents_mask')
i... |
def get_validation_parser(default_task=None):
parser = get_parser('Validation', default_task)
add_dataset_args(parser, train=True)
add_distributed_training_args(parser, default_world_size=1)
group = parser.add_argument_group('Evaluation')
gen_parser_from_dataclass(group, CommonEvalConfig())
retu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.