code stringlengths 281 23.7M |
|---|
class MaximumLikelihoodAmplitudeEstimation(AmplitudeEstimationAlgorithm):
def __init__(self, num_oracle_circuits: int, state_preparation: Optional[Union[(QuantumCircuit, CircuitFactory)]]=None, grover_operator: Optional[Union[(QuantumCircuit, CircuitFactory)]]=None, objective_qubits: Optional[List[int]]=None, post_... |
def test_rpcs():
rpcs = RPC(**TEST_RPCS_NATIVE_PYTHON)
for (key, value) in rpcs.to_dict().items():
assert (key in TEST_RPCS_NATIVE_PYTHON.keys())
assert (value == TEST_RPCS_NATIVE_PYTHON[key])
assert isinstance(value, (float, list))
if isinstance(value, list):
assert ... |
def validate_and_save(cfg: DictConfig, trainer: Trainer, task: tasks.FairseqTask, epoch_itr, valid_subsets: List[str], end_of_epoch: bool) -> Tuple[(List[Optional[float]], bool)]:
num_updates = trainer.get_num_updates()
max_update = (cfg.optimization.max_update or math.inf)
should_stop = False
if (num_u... |
def find_closest_psnr(target, img, fmt='jpeg'):
lower = 0
upper = 100
prev_mid = upper
def _psnr(a, b):
a = np.asarray(a).astype(np.float32)
b = np.asarray(b).astype(np.float32)
mse = np.mean(np.square((a - b)))
return ((20 * math.log10(255.0)) - (10.0 * math.log10(mse)))... |
class Encoder(nn.Module):
def __init__(self, d_model, d_ff, d_k, d_v, n_layers, n_heads, len_q):
super(Encoder, self).__init__()
self.layers = nn.ModuleList([EncoderLayer(d_model, d_ff, d_k, d_v, n_heads, len_q) for _ in range(n_layers)])
def forward(self, enc_inputs):
enc_outputs = enc_... |
class CoverPluginHandler(PluginHandler):
def __init__(self, use_built_in=True):
self.providers = set()
if use_built_in:
self.built_in = {built_in.EmbeddedCover, built_in.FilesystemCover}
else:
self.built_in = set()
def plugin_handle(self, plugin):
return i... |
def service_installed(service: str) -> bool:
if (not service.endswith('.service')):
service += '.service'
try:
out = subprocess.check_output(['systemctl', 'list-unit-files', service], text=True)
except subprocess.CalledProcessError:
return False
return (len(out.splitlines()) > 3) |
class Mode(ItemAttrShortcut, HandledItem):
def __init__(self, item, owner=None):
if (item.group.name != 'Ship Modifiers'):
raise ValueError(('Passed item "%s" (category: (%s)) is not a Ship Modifier' % (item.name, item.category.name)))
self.owner = owner
self.__item = item
... |
class Effect5918(BaseEffect):
runTime = 'early'
type = ('projected', 'passive')
def handler(fit, beacon, context, projectionRange, **kwargs):
fit.modules.filteredChargeMultiply((lambda mod: mod.charge.requiresSkill('Bomb Deployment')), 'thermalDamage', beacon.getModifiedItemAttr('smartbombDamageMult... |
class KeithleyBuffer():
buffer_points = Instrument.control(':TRAC:POIN?', ':TRAC:POIN %d', ' An integer property that controls the number of buffer points. This\n does not represent actual points in the buffer, but the configuration\n value instead. ', validator=truncated_range, values=[2, 1024], cast... |
def test_asking_qu_questions():
type_ = '_quservice._tcp.local.'
zeroconf = r.Zeroconf(interfaces=['127.0.0.1'])
old_send = zeroconf.async_send
first_outgoing = None
def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT):
nonlocal first_outgoing
if (first_outgoing is None):
... |
def getFiles(folder, suffix='.json', exclude=['results.json']):
file_list = []
for (root, _, filenames) in os.walk(folder):
for f in filenames:
if (f.endswith(suffix) and (f not in exclude)):
file_list.append(os.path.join(root, f))
file_list.sort()
return file_list |
class FakeNetCDF4FileHandler2(FakeNetCDF4FileHandler):
def get_test_content(self, filename, filename_info, filetype_info):
dt = filename_info.get('start_time', datetime(2016, 1, 1, 12, 0, 0))
(sat, inst) = {'VIIRS_NPP': ('NPP', 'VIIRS'), 'VIIRS_N20': ('N20', 'VIIRS')}[filename_info['sensor_id']]
... |
def test_sampling_no_nodata_masked_beyond_bounds(data):
filename = str(data.join('RGB.byte.tif'))
with rasterio.open(filename, 'r+') as src:
src.nodata = None
with rasterio.open(filename) as src:
data = next(src.sample([(0.0, 0.0)], masked=True))
assert numpy.ma.is_masked(data)
... |
class TestResamplerRegistryManipulation():
def setup_method(self):
_ = list_resamplers()
self.mock_reg = mock.patch('pyresample.future.resamplers.registry.RESAMPLER_REGISTRY', {})
self.mock_reg.start()
def teardown_method(self):
self.mock_reg.stop()
def test_no_builtins_warni... |
def test_cannot_update_a_grant_if_grants_are_closed(graphql_client, user, conference_factory, grant_factory):
graphql_client.force_login(user)
conference = conference_factory(active_grants=False)
grant = grant_factory(conference=conference, user_id=user.id)
response = _update_grant(graphql_client, grant... |
class Section():
def __init__(self, lc, data):
self.name = lc.section_name
self.segment_name = lc.segment_name
self.address = lc.address
self.size = lc.size
self.offset = lc.offset
self.align = lc.alignment
self.rel_offset = lc.relocations_offset
self.... |
def cfstring_to_string(cfstring):
length = cf.CFStringGetLength(cfstring)
size = cf.CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8)
buffer = c_buffer((size + 1))
result = cf.CFStringGetCString(cfstring, buffer, len(buffer), kCFStringEncodingUTF8)
if result:
return str(buffer... |
def DS_format_to_bert(pretrained_path, args):
corpora = {'train': [], 'val': [], 'test': []}
bert = BertData(pretrained_path, args)
read_root_path = Path(args.raw_path)
for corpus_type in corpora:
save_root_path = (Path(args.save_path) / corpus_type)
save_root_path.mkdir(exist_ok=True, p... |
class Artist():
def __init__(self, name, sort_name, id_):
self.name = name
self.sort_name = sort_name
self.id = id_
def is_various(self):
return (self.id == VARIOUS_ARTISTS_ARTISTID)
def from_credit(cls, mbcredit):
artists = []
for credit in mbcredit:
... |
class TestReportInfo():
def test_itemreport_reportinfo(self, pytester: Pytester) -> None:
pytester.makeconftest('\n import pytest\n class MyFunction(pytest.Function):\n def reportinfo(self):\n return "ABCDE", 42, "custom"\n def pytest_pycoll... |
def _create_post_title(config, show, episode):
if show.name_en:
title = config.post_title_with_en
else:
title = config.post_title
if ((episode.number == show.length) and config.post_title_postfix_final):
title += (' ' + config.post_title_postfix_final)
return title |
.filterwarnings('error:Duplicate name')
.parametrize('build_tag_arg, existing_build_tag, filename', [(None, None, 'test-1.0-py2.py3-none-any.whl'), ('2b', None, 'test-1.0-2b-py2.py3-none-any.whl'), (None, '3', 'test-1.0-3-py2.py3-none-any.whl'), ('', '3', 'test-1.0-py2.py3-none-any.whl')], ids=['nobuildnum', 'newbuilda... |
class ews_input_long(unittest.TestCase):
def test(self):
run_test(self, ['--ews', '01 1379 500'], ' Month/Day/Year H:M:S 06/11/2006 00:08:20 GPS\n Modified Julian Date 53897. GPS\n GPSweek DayOfWeek SecOfWeek 355 0 500.000000\n FullGPSweek Zcount ... |
def ss_multmodel_factory(nsamples, data_mods, data_lhs, idx=None):
for dm in data_mods:
dm.train()
for dlh in data_lhs:
dlh.train()
mll_list = [gpytorch.ExactMarginalLogLikelihood(dlh, dm) for (dlh, dm) in zip(data_lhs, data_mods)]
latent_lh = data_mods[0].covar_module.latent_lh
late... |
def find_dps(graph: DataPipeGraph, dp_type: Type[DataPipe]) -> List[DataPipe]:
dps: List[DataPipe] = []
cache: Set[int] = set()
def helper(g) -> None:
for (dp_id, (dp, src_graph)) in g.items():
if (dp_id in cache):
continue
cache.add(dp_id)
if (typ... |
class NegativeSampling(Strategy):
def __init__(self, model=None, loss=None, batch_size=256, regul_rate=0.0, l3_regul_rate=0.0):
super(NegativeSampling, self).__init__()
self.model = model
self.loss = loss
self.batch_size = batch_size
self.regul_rate = regul_rate
self.... |
class TestGVARFloat(unittest.TestCase):
def test_fun(self):
test_data = [((- 1.0), b'\xbe\xf0\x00\x00'), ((- 0.1640625), b'\xbf\xd6\x00\x00'), (0.0, b'\x00\x00\x00\x00'), (0.1640625, b'*\x00\x00'), (1.0, b'A\x10\x00\x00'), (, b'Bd*\x00')]
for (expected, str_val) in test_data:
val = np.fr... |
class FixedPropertyData(PropertyData):
def __init__(self, name, size):
PropertyData.__init__(self, name)
self.size = size
def parse_binary_value(self, data, display, length, format):
return PropertyData.parse_binary_value(self, data, display, (self.size // (format // 8)), format)
def... |
.parametrize('type_', _data.to.dtypes)
.parametrize(['operator', 'dispatch'], [pytest.param((lambda data, number: (data * number)), _data.mul, id='mul'), pytest.param((lambda data, number: (number * data)), _data.mul, id='rmul'), pytest.param((lambda data, number: (data / number)), (lambda data, number: _data.mul(data,... |
class ExpectedEnvVars():
def __init__(self, env_vars: dict):
self.env_vars = env_vars
def __eq__(self, other):
return all(((not ((key not in other) or (other[key] != value))) for (key, value) in self.env_vars.items()))
def __hash__(self):
return hash(self.env_vars) |
def test_is_currency():
assert is_currency('EUR')
assert (not is_currency('eUr'))
assert (not is_currency('FUU'))
assert (not is_currency(''))
assert (not is_currency(None))
assert (not is_currency(' EUR '))
assert (not is_currency(' '))
assert (not is_currency([]))
assert (no... |
class NoDuplicateOptWarningFilter(logging.Filter):
prev_msgs: set = set()
def filter(self, record):
msg = record.getMessage()
if msg.startswith('Optimization Warning: '):
if (msg in self.prev_msgs):
return False
else:
self.prev_msgs.add(msg... |
_loss('sum_arbitrary')
class SumArbitraryLoss(ClassyLoss):
def __init__(self, losses: List[ClassyLoss], weights: Optional[Tensor]=None) -> None:
super().__init__()
if (weights is None):
weights = torch.ones(len(losses))
self.losses = losses
self.weights = weights
def ... |
class BatchLexer(RegexLexer):
name = 'Batchfile'
aliases = ['batch', 'bat', 'dosbatch', 'winbatch']
filenames = ['*.bat', '*.cmd']
mimetypes = ['application/x-dos-batch']
url = '
version_added = '0.7'
flags = (re.MULTILINE | re.IGNORECASE)
_nl = '\\n\\x1a'
_punct = '&<>|'
_ws = '... |
class StataDarkStyle(Style):
name = 'stata-dark'
background_color = '#232629'
highlight_color = '#49483e'
styles = {Token: '#cccccc', Whitespace: '#bbbbbb', Error: 'bg:#e3d2d2 #a61717', String: '#51cc99', Number: '#4FB8CC', Operator: '', Name.Function: '#6a6aff', Name.Other: '#e2828e', Keyword: 'bold #7... |
class StaffPublisherReportView(BaseReportView):
force_revshare = 70.0
impression_model = PublisherPaidImpression
report = OptimizedPublisherPaidReport
template_name = 'adserver/reports/staff-publishers.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
... |
class TestEllipticCurvePEMPublicKeySerialization():
.parametrize(('key_path', 'loader_func', 'encoding'), [(os.path.join('asymmetric', 'PEM_Serialization', 'ec_public_key.pem'), serialization.load_pem_public_key, serialization.Encoding.PEM), (os.path.join('asymmetric', 'DER_Serialization', 'ec_public_key.der'), ser... |
class _ExpectFeedback(_Feedback):
def __init__(self, oper, default=0.0):
self.oper = QobjEvo(oper)
self.N = oper.shape[1]
self.N2 = (oper.shape[1] ** 2)
self.default = default
def check_consistency(self, dims):
if (not ((self.oper._dims == dims) or (self.oper._dims[1] == ... |
class ctx(object):
def __init__(self, kwd_dict=None, **kwds):
self.kwds = (kwd_dict or kwds)
def __enter__(self):
_ctx.clear()
for (k, v) in self.kwds.items():
_ctx.add(k, v)
return self
def __exit__(self, exc_type=None, exc_val=None, exc_tb=None):
self.kw... |
def test_customizations(ansi_io: BufferedIO) -> None:
bar = ProgressBar(ansi_io, 10, 0)
bar.set_bar_width(10)
bar.set_bar_character('_')
bar.set_empty_bar_character(' ')
bar.set_progress_character('/')
bar.set_format(' %current%/%max% [%bar%] %percent:3s%%')
bar.start()
bar.advance()
... |
def _is_property_decorator(decorator):
def _is_property_class(class_node):
return ((class_node.name == 'property') and (class_node.root().name == builtins.__name__))
for inferred in decorator.infer():
if (not isinstance(inferred, astroid.nodes.ClassDef)):
continue
if _is_prop... |
def events_for_onchain_secretreveal(channel_state: NettingChannelState, secret: Secret, expiration: BlockExpiration, block_hash: BlockHash) -> List[Event]:
events: List[Event] = []
typecheck(secret, T_Secret)
if (get_status(channel_state) in CHANNEL_STATES_UP_TO_CLOSED):
reveal_event = ContractSendS... |
def total_norm_constraint(tensor_vars, max_norm, epsilon=1e-07, return_norm=False):
norm = pt.sqrt(sum((pt.sum((tensor ** 2)) for tensor in tensor_vars)))
dtype = np.dtype(pytensor.config.floatX).type
target_norm = pt.clip(norm, 0, dtype(max_norm))
multiplier = (target_norm / (dtype(epsilon) + norm))
... |
def test_exception_lookup_last_except_handler_wins() -> None:
node = extract_node('\n try:\n 1/0\n except ValueError as exc:\n pass\n try:\n 1/0\n except OSError as exc:\n exc #\n ')
assert isinstance(node, nodes.NodeNG)
inferred = node.inferred()
assert (len(i... |
def bin_bloq_counts(bloq: Bloq) -> Dict[(str, int)]:
classified_bloqs = defaultdict(int)
for (bloq, num_calls) in bloq.bloq_counts().items():
if isinstance(bloq, (Split, Join, Allocate, Free)):
continue
num_t = bloq.call_graph(generalizer=GENERALIZERS)[1].get(TGate())
if (num... |
class VkKeyboard(object):
__slots__ = ('one_time', 'lines', 'keyboard', 'inline')
def __init__(self, one_time=False, inline=False):
self.one_time = one_time
self.inline = inline
self.lines = [[]]
self.keyboard = {'one_time': self.one_time, 'inline': self.inline, 'buttons': self.l... |
.parametrize(('damage', 'items', 'requirement'), [(50, [], _arr_req('and', [_json_req(50)])), (MAX_DAMAGE, [], _arr_req('and', [_json_req(1, 'Dark', ResourceType.ITEM)])), (80, [], _arr_req('and', [_json_req(50), _json_req(30)])), (30, [], _arr_req('or', [_json_req(50), _json_req(30)])), (50, [], _arr_req('or', [_json_... |
def test_hashgrid_query(test, device):
grid = wp.HashGrid(dim_x, dim_y, dim_z, device)
for i in range(num_runs):
if print_enabled:
print(f'Run: {(i + 1)}')
print('')
np.random.seed(532)
points = ((np.random.rand(num_points, 3) * scale) - (np.array((scale, scale, s... |
class Effect1007(BaseEffect):
type = 'passive'
def handler(fit, skill, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Small Autocannon Specialization')), 'damageMultiplier', (skill.getModifiedItemAttr('damageMultiplierBonus') * skill.level), **kwa... |
def create_labels(num_rows: int, num_classes: int=2, dtype: Optional[np.dtype]=None):
if (num_classes == 0):
dtype = (dtype or np.float32)
return pd.Series(np.random.uniform(0, 1, size=num_rows), dtype=dtype, name='label')
dtype = (dtype or np.int32)
return pd.Series(np.random.randint(0, num... |
def post_callback(request):
metadata = request.get_metadata()
sorted_metadata = sorted(metadata.items(), key=(lambda x: (x[0] if ('Awb' not in x[0]) else f'Z{x[0]}')))
pretty_metadata = []
for (k, v) in sorted_metadata:
row = ''
try:
iter(v)
if (k == 'ColourCorrec... |
class TTPE2(TestCase):
def test_unsynch(self):
header = ID3Header()
header.version = (2, 4, 0)
header._flags = 128
badsync = b'\x00\xff\x00ab\x00'
self.assertEquals(TPE2._fromData(header, 0, badsync), [u'yab'])
header._flags = 0
self.assertEquals(TPE2._fromDat... |
class SignalsRegister(metaclass=abc.ABCMeta):
def save_signals(self, signals: List[Signal]):
raise NotImplementedError()
def get_signals(self) -> QFDataFrame:
raise NotImplementedError()
def get_signals_for_ticker(self, ticker: Optional[Ticker], alpha_model=None) -> QFSeries:
raise N... |
def get_values(hive, key):
vdict = {}
cmd = ops.cmd.getDszCommand('registryquery')
cmd.hive = hive
cmd.key = key
obj = cmd.execute()
if cmd.success:
for key in obj.key:
for value in key.value:
vdict[value.name] = value.value
return vdict |
('pypyr.steps.dsl.fileinoutrewriter.ObjectRewriter', spec=ObjectRewriter)
def test_objectrewriterstep_run_step_no_out(mock_rewriter):
context = Context({'root': {'in': 'inpathhere'}})
obj = ObjectRewriterStep('blah.name', 'root', context)
assert (obj.path_in == 'inpathhere')
assert (not obj.path_out)
... |
def create_lmdb_for_div2k():
folder_path = 'datasets/DIV2K/DIV2K_train_HR_sub'
lmdb_path = 'datasets/DIV2K/DIV2K_train_HR_sub.lmdb'
(img_path_list, keys) = prepare_keys_div2k(folder_path)
make_lmdb_from_imgs(folder_path, lmdb_path, img_path_list, keys)
folder_path = 'datasets/DIV2K/DIV2K_train_LR_bi... |
class DictObjectModelTest(unittest.TestCase):
def test__class__(self) -> None:
ast_node = builder.extract_node('{}.__class__')
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, astroid.ClassDef)
self.assertEqual(inferred.name, 'dict')
def test_attributes_inferred_... |
def test_args_refcount():
refcount = m.arg_refcount_h
myval = 54321
expected = refcount(myval)
assert (m.arg_refcount_h(myval) == expected)
assert (m.arg_refcount_o(myval) == (expected + 1))
assert (m.arg_refcount_h(myval) == expected)
assert (refcount(myval) == expected)
assert (m.mixed... |
class ProjectForm(forms.ModelForm):
use_required_attribute = False
def __init__(self, *args, **kwargs):
catalogs = kwargs.pop('catalogs')
projects = kwargs.pop('projects')
super().__init__(*args, **kwargs)
self.fields['title'].widget.attrs.update({'autofocus': True})
self... |
class RemoteGraphicsView(QtWidgets.QWidget):
def __init__(self, parent=None, *args, **kwds):
self._img = None
self._imgReq = None
self._sizeHint = (640, 480)
QtWidgets.QWidget.__init__(self)
remoteKwds = {}
for kwd in ['useOpenGL', 'background']:
if (kwd i... |
class Bubble(object):
def __init__(self, position, radius, velocity):
self.position = position
self.vel = velocity
self.radius = radius
self.innerColor = self.randomColor()
self.outerColor = self.randomColor()
self.updateBrush()
def updateBrush(self):
grad... |
class bdist_wheel(Command):
description = 'create a wheel distribution'
supported_compressions = {'stored': ZIP_STORED, 'deflated': ZIP_DEFLATED}
user_options = [('bdist-dir=', 'b', 'temporary directory for creating the distribution'), ('plat-name=', 'p', ('platform name to embed in generated filenames (def... |
class DropoutWrapper(nn.Module):
def __init__(self, dropout_p=0, enable_vbp=True):
super(DropoutWrapper, self).__init__()
self.enable_variational_dropout = enable_vbp
self.dropout_p = dropout_p
def forward(self, x):
if ((self.training == False) or (self.dropout_p == 0)):
... |
class Stem(nn.Module):
def __init__(self, in_chs: int, out_chs: int, kernel_size: int=3, padding: str='', bias: bool=False, act_layer: str='gelu', norm_layer: str='batchnorm2d', norm_eps: float=1e-05):
super().__init__()
if (not isinstance(out_chs, (list, tuple))):
out_chs = to_2tuple(ou... |
def _populate_kernel_cache(np_type, k_type):
if (np_type not in _SUPPORTED_TYPES):
raise ValueError("Datatype {} not found for '{}'".format(np_type, k_type))
if ((str(np_type), k_type) in _cupy_kernel_cache):
return
_cupy_kernel_cache[(str(np_type), k_type)] = _get_function('/io/_reader.fatb... |
_combinator('and')
class AndFilter(BaseFilter):
def __init__(self, stack):
self.subfilters = [stack[(- 2)], stack[(- 1)]]
stack.pop()
stack.pop()
stack.append(self)
def __call__(self, fobj):
return accept_file(fobj, self.subfilters)
def __str__(self):
return '... |
class GaussianStatePreparationCircuitTest(unittest.TestCase):
def setUp(self):
self.n_qubits_range = range(3, 6)
def test_ground_state_particle_conserving(self):
for n_qubits in self.n_qubits_range:
print(n_qubits)
quadratic_hamiltonian = random_quadratic_hamiltonian(n_qu... |
def get_map(Hist) -> np.ndarray:
sum_Hist = sum(Hist)
Pr = (Hist / sum_Hist)
Sk = []
temp_sum = 0
for n in Pr:
temp_sum = (temp_sum + n)
Sk.append(temp_sum)
Sk = np.array(Sk)
img_map = []
for m in range(256):
temp_map = int(((255 * Sk[m]) + 0.5))
img_map.a... |
def partition_all(n, seq):
args = ([iter(seq)] * n)
it = zip_longest(*args, fillvalue=no_pad)
try:
prev = next(it)
except StopIteration:
return
for item in it:
(yield prev)
prev = item
if (prev[(- 1)] is no_pad):
try:
(yield prev[:(len(seq) % n... |
def pylsp_references(document, position, exclude_declaration):
code_position = _utils.position_to_jedi_linecolumn(document, position)
usages = document.jedi_script().get_references(**code_position)
if exclude_declaration:
usages = [d for d in usages if (not d.is_definition())]
return [{'uri': (u... |
def main():
print('Loading CUB trainset')
trainset = CUB(input_size=input_size, root=root, is_train=True, model_type=model_type)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=8, drop_last=False)
print('Loading CUB testset')
testset = CUB(input_s... |
class CuArray():
def __init__(self, shape, dtype=np.float32, init='empty', grow_only=False):
self._ptr = c_void_p()
self.grow_only = grow_only
self.resize(shape, dtype, init)
def resize(self, shape=None, dtype=None, init='empty'):
shape_tuple = (shape if isinstance(shape, tuple) ... |
class Nest(nn.Module):
def __init__(self, img_size=224, in_chans=3, patch_size=4, num_levels=3, embed_dims=(128, 256, 512), num_heads=(4, 8, 16), depths=(2, 2, 20), num_classes=1000, mlp_ratio=4.0, qkv_bias=True, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.5, norm_layer=None, act_layer=None, pad_type='', we... |
class FC3Handler(BaseHandler):
version = FC3
commandMap = {'auth': commands.authconfig.FC3_Authconfig, 'authconfig': commands.authconfig.FC3_Authconfig, 'autopart': commands.autopart.FC3_AutoPart, 'autostep': commands.autostep.FC3_AutoStep, 'bootloader': commands.bootloader.FC3_Bootloader, 'cdrom': commands.cdr... |
class VanEncoder(nn.Module):
def __init__(self, config: VanConfig):
super().__init__()
self.stages = nn.ModuleList([])
patch_sizes = config.patch_sizes
strides = config.strides
hidden_sizes = config.hidden_sizes
depths = config.depths
mlp_ratios = config.mlp_r... |
def _spin_hamiltonian(N):
from qutip.core import tensor, qeye, sigmax, sigmay, sigmaz
h = (((2 * np.pi) * 1.0) * np.ones(N))
Jz = (((2 * np.pi) * 0.1) * np.ones(N))
Jx = (((2 * np.pi) * 0.1) * np.ones(N))
Jy = (((2 * np.pi) * 0.1) * np.ones(N))
si = qeye(2)
sx = sigmax()
sy = sigmay()
... |
class BosonicBath(Bath):
def _check_cks_and_vks(self, ck_real, vk_real, ck_imag, vk_imag):
if ((len(ck_real) != len(vk_real)) or (len(ck_imag) != len(vk_imag))):
raise ValueError('The bath exponent lists ck_real and vk_real, and ck_imag and vk_imag must be the same length.')
def _check_coup_... |
def append_call_sample_docstring(model_class, checkpoint, output_type, config_class, mask=None):
model_class.__call__ = copy_func(model_class.__call__)
model_class.__call__ = add_code_sample_docstrings(checkpoint=checkpoint, output_type=output_type, config_class=config_class, model_cls=model_class.__name__)(mod... |
def save_datasets(ds_train: List[ContextualizedExample], ds_dev: List[ContextualizedExample], output_dir):
utils.IO.ensure_dir(output_dir)
output_file = Path(output_dir, f'train.jsonl')
logger.warning(f'Saving to {output_file}')
output_objs = []
for example in ds_train:
output_objs.append(ex... |
def test_jac_method_grad():
na = 3
params = getfnparams(na)
nnparams = getnnparams(na)
num_nnparams = len(nnparams)
jacs = jac(func2(*nnparams), params)
nout = jacs[0].shape[(- 2)]
def fcnr(i, v, *allparams):
nnparams = allparams[:num_nnparams]
params = allparams[num_nnparams... |
class TestNoMaterial(TestWavefront):
def setUp(self):
self.mesh_names = ['Simple', 'SimpleB']
self.material_names = ['default0']
self.meshes = pywavefront.Wavefront(fixture('simple_no_mtl.obj'))
def testMeshMaterialVertices(self):
self.assertEqual(len(self.meshes.meshes[self.mesh... |
class DropDB(ProductionCommand):
keyword = 'dropdb'
def assemble(self):
super().assemble()
self.parser.add_argument('-y', '--yes', action='store_true', dest='yes', help='automatically answers yes on prompts')
self.parser.add_argument('-U', '--super-user-name', dest='super_user_name', def... |
class ResNet(nn.Module):
def __init__(self, depth, num_filters, block_name='BasicBlock', num_classes=10):
super(ResNet, self).__init__()
if (block_name.lower() == 'basicblock'):
assert (((depth - 2) % 6) == 0), 'When use basicblock, depth should be 6n+2, e.g. 20, 32, 44, 56, 110, 1202'
... |
(epilog=merge_epilog)
('--title', help='Title to use for the output file')
('--output', '-o', 'output_filename', default=None, type=click.Path(), help='The output database filename (the default is "merged.mmpdb")')
_multiple_databases_parameters()
('--verify', type=click.Choice(['off', 'options', 'constants', 'all']), ... |
def install_emc(args):
emc_path = os.path.join(FAKE_DIRECTORY, 'kernel/debug', 'bpmp/debug/clk/emc')
if (not os.path.isdir(emc_path)):
print('The directory {path} is not present. Creating a new one..'.format(path=emc_path))
os.makedirs(emc_path)
write_on_file(os.path.join(emc_path, 'rate'), ... |
def check_input_dir(fs_dir, user_dir, vis_type, freesurfer_install_required=True):
in_dir = fs_dir
if ((fs_dir is None) and (user_dir is None)):
raise ValueError('At least one of --fs_dir or --user_dir must be specified.')
if (fs_dir is not None):
if (user_dir is not None):
raise... |
class ViewSwitchIpDetail(db.Model):
__tablename__ = 'tb_view_switch_ip_detail'
id = db.Column(db.Integer, primary_key=True)
switch_id = db.Column(db.Integer, nullable=False)
domain_name = db.Column(db.String(256), nullable=False, primary_key=True)
before_enabled_server_rooms = db.Column(db.String(25... |
class OpTypePattern(Pattern):
def __init__(self, op_type, name=None, inputs=None, ordered_inputs=True):
self._op_type = op_type
self._name = name
if (inputs is None):
inputs = []
if (len(inputs) > 8):
raise ValueError('Only < 8 inputs are allowed when ordered_... |
def plot_slit(w, I=None, wunit='', plot_unit='same', Iunit=None, warnings=True, ls='-', title=None, waveunit=None):
if (waveunit is not None):
warn('`waveunit=` parameter in convolve_with_slit is now named `wunit=`', DeprecationWarning)
wunit = waveunit
import matplotlib.pyplot as plt
from r... |
class IgnoredUnusedAttributes(StringSequenceOption):
name = 'ignored_unused_attributes'
default_value = ['_abc_cache', '_abc_negative_cache', '__abstractmethods__', '_abc_negative_cache_version', '_abc_registry', '__module__', '__doc__', '__init__', '__dict__', '__weakref__', '__enter__', '__exit__', '__metacla... |
def build_train_valid_test_data_iterators(build_train_valid_test_datasets_provider):
args = get_args()
(train_dataloader, valid_dataloader, test_dataloader) = (None, None, None)
print_rank_0('> building train, validation, and test datasets ...')
if (mpu.get_model_parallel_rank() == 0):
data_para... |
class SectionArgspathWrapper(Dataset):
def __init__(self, dataset, section, args_path):
self.dataset = dataset
self.section = section
self.args_path = args_path
def __getitem__(self, index):
item = self.dataset[index]
item['section'] = self.section
item['arg_path'... |
class SpatialDropout1D(Dropout):
_spatialdropout1d_support
def __init__(self, rate, **kwargs):
super(SpatialDropout1D, self).__init__(rate, **kwargs)
self.input_spec = InputSpec(ndim=3)
def _get_noise_shape(self, inputs):
input_shape = K.shape(inputs)
noise_shape = (input_sha... |
def squad_convert_examples_to_features(examples, tokenizer, max_seq_length, doc_stride, max_query_length, is_training, padding_strategy='max_length', return_dataset=False, threads=1, tqdm_enabled=True):
features = []
threads = min(threads, cpu_count())
with Pool(threads, initializer=squad_convert_example_to... |
def expected_protocol(instrument_cls, comm_pairs, connection_attributes={}, connection_methods={}, **kwargs):
protocol = ProtocolAdapter(comm_pairs, connection_attributes=connection_attributes, connection_methods=connection_methods)
instr = instrument_cls(protocol, **kwargs)
(yield instr)
assert (protoc... |
class DummyStateMachine(StateMachineWS):
def __init__(self):
self.memo = Struct(title_styles=[], inliner=None)
self.state = RSTState(self)
self.input_offset = 0
def reset(self, document, parent, level):
self.language = languages.get_language(document.settings.language_code)
... |
class _FragList():
flist: list[bytes]
def __init__(self, init: (list[bytes] | None)=None) -> None:
self.flist = []
if init:
self.flist.extend(init)
def put_raw(self, val: bytes) -> None:
self.flist.append(val)
def put_u32(self, val: int) -> None:
self.flist.ap... |
def change_name_color(caller, treestr, index, selection):
if (not caller.db.uncolored_name):
caller.db.uncolored_name = caller.key
colordict = {'Red': '|511', 'Pink': '|533', 'Maroon': '|301', 'Orange': '|531', 'Brown': '|321', 'Sienna': '|420', 'Yellow': '|551', 'Gold': '|540', 'Dandelion': '|553', 'Gr... |
def test_tree_max_product_tree():
try:
from scipy.sparse.csgraph import minimum_spanning_tree
except:
raise SkipTest('Not testing trees, scipy version >= 0.11 required')
rnd = np.random.RandomState(0)
for i in range(100):
graph = rnd.uniform(size=(10, 10))
tree = minimum_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.