code stringlengths 281 23.7M |
|---|
def test_pad_sequences():
a = [[1], [1, 2], [1, 2, 3]]
b = pad_sequences(a, maxlen=3, padding='pre')
assert_allclose(b, [[0, 0, 1], [0, 1, 2], [1, 2, 3]])
b = pad_sequences(a, maxlen=3, padding='post')
assert_allclose(b, [[1, 0, 0], [1, 2, 0], [1, 2, 3]])
b = pad_sequences(a, maxlen=2, truncatin... |
(cc=STDCALL, params={'nCount': DWORD, 'lpHandles': HANDLE, 'bWaitAll': BOOL, 'dwMilliseconds': DWORD})
def hook_WaitForMultipleObjects(ql: Qiling, address: int, params):
nCount = params['nCount']
lpHandles = params['lpHandles']
for i in range(nCount):
handle_value = ql.unpack(ql.mem.read((lpHandles ... |
_test
def test_zeropadding3d_legacy_interface():
old_layer = keras.layers.ZeroPadding3D((2, 2, 2), dim_ordering='tf', name='zp3d')
new_layer = keras.layers.ZeroPadding3D((2, 2, 2), data_format='channels_last', name='zp3d')
assert (json.dumps(old_layer.get_config()) == json.dumps(new_layer.get_config())) |
class VTAnalysis():
def __init__(self, api_keys_list, waiting_time=16):
self.REPORT_URL = '
self.SCAN_URL = '
self.api_keys_list = {}
for api_key in api_keys_list:
self.api_keys_list[api_key] = True
self.api_key = api_keys_list[0]
self.reports = {}
... |
def setup_intersphinx(app, config):
if (not app.config.hoverxref_intersphinx):
return
if (sphinx.version_info < (3, 0, 0)):
listeners = list(app.events.listeners.get('missing-reference').items())
else:
listeners = [(listener.id, listener.handler) for listener in app.events.listeners.... |
def _is_unnecessary_indexing(node: Union[(nodes.For, nodes.Comprehension)]) -> bool:
index_nodes = []
for assign_name_node in node.target.nodes_of_class((nodes.AssignName, nodes.Name)):
index_nodes.extend(_index_name_nodes(assign_name_node.name, node))
return (all((_is_redundant(index_node, node) fo... |
def test_global_pool_cell():
inputs_x = torch.randn([2, 256, 32, 32])
inputs_y = torch.randn([2, 256, 32, 32])
gp_cell = GlobalPoolingCell(with_out_conv=False)
gp_cell_out = gp_cell(inputs_x, inputs_y, out_size=inputs_x.shape[(- 2):])
assert (gp_cell_out.size() == inputs_x.size())
gp_cell = Glob... |
class BrokenUserTests(unittest.TestCase):
def setUp(self):
self.user = BrokenUser
def tearDown(self):
self.user = None
def test_get_username(self):
with self.assertRaisesRegex(NotImplementedError, NOT_IMPLEMENTED_MSG):
self.user.get_username(User('foobar'))
def test_u... |
class TestNoReturn(TestNameCheckVisitorBase):
_passes()
def test_no_return(self):
from typing import Optional
from typing_extensions import NoReturn
def f() -> NoReturn:
raise Exception
def capybara(x: Optional[int]) -> None:
if (x is None):
... |
def test_raise_error_with_builtin_function_as_task(runner, tmp_path):
source = '\n from pytask import task\n from pathlib import Path\n from datetime import datetime\n\n task(\n kwargs={"format": "%y/%m/%d"}, produces=Path("time.txt")\n )(datetime.utcnow().strftime)\n '
tmp_path.joinpat... |
class StubQuery(object):
def __init__(self, model):
self.model = model
self.order_by = ['pk']
def select_related(self):
return False
def add_context(self, *args, **kwargs):
pass
def get_context(self, *args, **kwargs):
return {}
def get_meta(self):
retu... |
.parametrize('public_catalog, credentials, expected_repos', [(False, None, None), (True, None, ['public/publicrepo']), (False, ('devtable', 'password'), ['devtable/simple', 'devtable/complex', 'devtable/gargantuan']), (True, ('devtable', 'password'), ['devtable/simple', 'devtable/complex', 'devtable/gargantuan'])])
.pa... |
_register
class StreamPropertiesObject(BaseObject):
GUID = guid2bytes('B7DC0791-A9B7-11CF-8EE6-00C00C205365')
def parse(self, asf, data):
super(StreamPropertiesObject, self).parse(asf, data)
(channels, sample_rate, bitrate) = struct.unpack('<HII', data[56:66])
asf.info.channels = channel... |
class GaussianProcessLogLikelihoodInterface(with_metaclass(ABCMeta, GaussianProcessDataInterface)):
def dim(self):
pass
def num_hyperparameters(self):
pass
def get_hyperparameters(self):
pass
def set_hyperparameters(self, hyperparameters):
pass
hyperparameters = abstr... |
class SRMFile(cpi.File):
def __init__(self, api, adaptor):
_cpi_base = super(SRMFile, self)
_cpi_base.__init__(api, adaptor)
def _dump(self):
print(('url : %s' % self._url))
print(('flags : %s' % self._flags))
print(('session: %s' % self._session))
def _alive(self... |
def create_csp_stem(in_chans=3, out_chs=32, kernel_size=3, stride=2, pool='', padding='', act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d, aa_layer=None):
stem = nn.Sequential()
feature_info = []
if (not isinstance(out_chs, (tuple, list))):
out_chs = [out_chs]
stem_depth = len(out_chs)
assert s... |
def read_embeddings(file_enc, skip_lines=0, filter_set=None):
embs = dict()
total_vectors_in_file = 0
with open(file_enc, 'rb') as f:
for (i, line) in enumerate(f):
if (i < skip_lines):
continue
if (not line):
break
if (len(line) ==... |
class TestSetAssertions():
.parametrize('op', ['>=', '>', '<=', '<', '=='])
def test_set_extra_item(self, op, pytester: Pytester) -> None:
pytester.makepyfile(f'''
def test_hello():
x = set("hello x")
y = set("hello y")
assert x {op} y
... |
('pypyr.moduleloader.get_module')
(Step, 'invoke_step', side_effect=mock_step_mutating_run)
def test_foreach_evaluates_run_decorator(mock_invoke, mock_moduleloader):
step = Step({'name': 'step1', 'run': '{dynamic_run_expression}', 'foreach': ['{key1}', '{key2}', 'key3']})
context = get_test_context()
contex... |
def sharp_iferror(extr, test, then='', Else=None, *args):
if re.match('<(?:strong|span|p|div)\\s(?:[^\\s>]*\\s+)*?class="(?:[^"\\s>]*\\s+)*?error(?:\\s[^">]*)?"', test):
return extr.expand(then.strip())
elif (Else is None):
return test.strip()
else:
return extr.expand(Else.strip()) |
class ELF32_Sym(ELF_Sym):
Sym_SIZE = (4 * 4)
def __init__(self, buf, endian=0):
if (len(buf) != self.Sym_SIZE):
raise
self.fmt = ('<IIIBBH' if (endian == 0) else '>IIIBBH')
(st_name, st_value, st_size, st_info, st_other, st_shndx) = struct.unpack(self.fmt, buf)
super(... |
.skipif((not is_py39_plus), reason='3.9+ only')
def test_annotated_attrs():
from typing import Annotated
converter = Converter()
class Inner():
a: int
class Outer():
i: Annotated[(Inner, 'test')]
j: list[Annotated[(Inner, 'test')]]
orig = Outer(Inner(1), [Inner(1)])
raw =... |
class Effect5300(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.drones.filteredItemBoost((lambda mod: mod.item.requiresSkill('Drones')), 'shieldCapacity', src.getModifiedItemAttr('shipBonusAD1'), skill='Amarr Destroyer', **kwargs)
fit.drones.filtered... |
def test_utf8_bom(gm_manager):
script = textwrap.dedent('\n \ufeff// ==UserScript==\n // qutebrowser test userscript\n // ==/UserScript==\n '.lstrip('\n'))
_save_script(script, 'bom.user.js')
gm_manager.load_scripts()
scripts = gm_manager.all_scripts()
assert (len(scripts) =... |
class StatReporter(PlainReporter):
error_messages = []
style_messages = []
def __init__(self, source_lines=None):
super().__init__(source_lines)
StatReporter.error_messages = []
StatReporter.style_messages = []
def print_messages(self, level='all'):
StatReporter.error_mes... |
class UnicornTask():
def __init__(self, uc: Uc, begin: int, end: int, task_id=None):
self._uc = uc
self._begin = begin
self._end = end
self._stop_request = False
self._ctx = None
self._task_id = None
self._arch = self._uc._arch
self._mode = self._uc._m... |
def infer_dtype_from_tensor(data: Union[(PackedMap, PackedList, List, torch.Tensor, Tuple)]):
if isinstance(data, WithPresence):
t = infer_dtype_from_tensor(data.values)
if t.nullable:
raise TypeError("WithPresence structs can't be nested")
return t.with_null()
if isinstance(... |
def trigger_update(distribution, for_py_version, wheel, search_dirs, app_data, env, periodic):
wheel_path = (None if (wheel is None) else str(wheel.path))
cmd = [sys.executable, '-c', dedent('\n from virtualenv.report import setup_report, MAX_LEVEL\n from virtualenv.seed.wheels.periodic_update imp... |
.parametrize('shift', [1.5, np.array([(- 0.5), 1, 0.3])])
.parametrize('scale', [2.0, np.array([1.5, 3.3, 1.0])])
def test_multivariate_rv_transform(shift, scale):
mu = np.array([0, 0.9, (- 2.1)])
cov = np.array([[1, 0, 0.9], [0, 1, 0], [0.9, 0, 1]])
x_rv_raw = pt.random.multivariate_normal(mu, cov=cov)
... |
class KBKDFCMAC(KeyDerivationFunction):
def __init__(self, algorithm, mode: Mode, length: int, rlen: int, llen: (int | None), location: CounterLocation, label: (bytes | None), context: (bytes | None), fixed: (bytes | None), backend: typing.Any=None, *, break_location: (int | None)=None):
if ((not issubclass... |
class GreeterStub():
def __init__(self, channel):
self._client = purerpc.Client('Greeter', channel)
self.SayHello = self._client.get_method_stub('SayHello', purerpc.RPCSignature(purerpc.Cardinality.UNARY_UNARY, generated.greeter_pb2.HelloRequest, generated.greeter_pb2.HelloReply))
self.SayHe... |
def _create_sigma_widgets() -> dict[(str, tuple[(str, QtWidgets.QWidget)])]:
P_sigma = QtWidgets.QDoubleSpinBox()
P_sigma.setRange(0, 500)
P_sigma.setStepType(QtWidgets.QAbstractSpinBox.AdaptiveDecimalStepType)
P_sigma.setToolTip('Magnitude of error in initial estimates.\nUsed to scale the matrix P.')
... |
('the width of cell {n_str} is {inches_str} inches')
def then_the_width_of_cell_n_is_x_inches(context, n_str, inches_str):
def _cell(table, idx):
(row, col) = ((idx // 3), (idx % 3))
return table.cell(row, col)
(idx, inches) = ((int(n_str) - 1), float(inches_str))
cell = _cell(context.table_... |
def _forgiving_version(version):
version = version.replace(' ', '.')
match = _PEP440_FALLBACK.search(version)
if match:
safe = match['safe']
rest = version[len(safe):]
else:
safe = '0'
rest = version
local = f'sanitized.{_safe_segment(rest)}'.strip('.')
return f'{... |
def create_quantizable_transformer_decoder_layer(transformerDecoderLayer: torch.nn.TransformerDecoderLayer) -> QuantizableTransformerDecoderLayer:
if isinstance(transformerDecoderLayer.activation, (torch.nn.modules.activation.ReLU, torch.nn.functional.relu)):
activation = 'relu'
elif isinstance(transfor... |
def can_create_user(email_address, blacklisted_domains=None):
if (features.BLACKLISTED_EMAILS and email_address and ('' in email_address)):
blacklisted_domains = (blacklisted_domains or [])
(_, email_domain) = email_address.split('', 1)
extracted = tldextract.extract(email_domain)
if... |
def fr_department(value: typing.Union[(str, int)]):
if (not value):
return False
if isinstance(value, str):
if (value in ('2A', '2B')):
return True
try:
value = int(value)
except ValueError:
return False
return ((1 <= value <= 19) or (21 <=... |
class DOE(ABC):
def __init__(self):
pass
def get_transmittance(self, xx, yy, ):
pass
def __add__(self, DOE2):
return DOE_mix(self, DOE2)
def get_E(self, E, xx, yy, ):
return (E * self.get_transmittance(xx, yy, ))
def get_coherent_PSF(self, xx, yy, z, ):
(xx, y... |
def _get_command_line_arguments():
parser = argparse.ArgumentParser()
parser.add_argument(('--' + Args.REPORT_DATA_PICKLES), help='Pickle files with the ReportData objects', required=True, nargs='+')
parser.add_argument(('--' + Args.RUN_NAMES), help='A name for each run', required=True, nargs='+')
parse... |
class LayoutLMConfig(BertConfig):
model_type = 'layoutlm'
def __init__(self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2, init... |
def _do_new(bz, opt, parser):
def parse_multi(val):
return _parse_triset(val, checkplus=False, checkminus=False, checkequal=False, splitcomma=True)[0]
kwopts = {}
if opt.blocked:
kwopts['blocks'] = parse_multi(opt.blocked)
if opt.cc:
kwopts['cc'] = parse_multi(opt.cc)
if opt.... |
class ThreadMonitor():
source = None
graph = {}
def __init__(self, func, *args, **kwargs) -> Callable:
self.func = func
self.shared_memory = kwargs['shared_memory']
self.sleep = kwargs['sleep']
self.cache = kwargs['cache']
self.timeout = kwargs['timeout']
self... |
class SnekAPITestCase(testing.TestCase):
def setUp(self):
super().setUp()
self.patcher = mock.patch('snekbox.api.snekapi.NsJail', autospec=True)
self.mock_nsjail = self.patcher.start()
self.mock_nsjail.return_value.python3.return_value = EvalResult(args=[], returncode=0, stdout='outp... |
class WindowsFile(File):
def exists(self):
return (self.check_output('powershell -command \\"Test-Path \'%s\'\\"', self.path) == 'True')
def is_file(self):
return (self.check_output('powershell -command \\"(Get-Item \'%s\') -is [System.IO.FileInfo]\\"', self.path) == 'True')
def is_directory... |
def test_used_with_class_scope(testdir: Any) -> None:
testdir.makeini('\n [pytest]\n asyncio_mode=auto\n ')
testdir.makepyfile('\n import pytest\n import random\n import unittest\n\n def get_random_number():\n return random.randint(0, 1)\n\n (au... |
class Migration(migrations.Migration):
dependencies = [('sponsors', '0059_auto__1503')]
operations = [migrations.AddField(model_name='logoplacement', name='describe_as_sponsor', field=models.BooleanField(default=False)), migrations.AddField(model_name='logoplacement', name='link_to_sponsors_page', field=models.... |
('/v1/repository/<apirepopath:repository>/permissions/user/<username>/transitive')
_param('repository', 'The full path of the repository. e.g. namespace/name')
_param('username', 'The username of the user to which the permissions apply')
class RepositoryUserTransitivePermission(RepositoryParamResource):
_repo_admin... |
def test_add_without_query(local_client: QdrantClient=QdrantClient(':memory:'), collection_name: str='demo_collection', docs: List[str]=None):
if (docs is None):
docs = ['Qdrant has Langchain integrations', 'Qdrant also has Llama Index integrations']
if (not local_client._is_fastembed_installed):
... |
class LoaderParser():
parsers = {}
def parse(self):
try:
return self.obj
except AttributeError:
pass
obj = self.parsers[self.catalog.format](self.data, self)
obj.item = self
obj.catalog = self.catalog.name
self.obj = obj
return obj |
class X448PrivateKey(metaclass=abc.ABCMeta):
def generate(cls) -> X448PrivateKey:
from cryptography.hazmat.backends.openssl.backend import backend
if (not backend.x448_supported()):
raise UnsupportedAlgorithm('X448 is not supported by this version of OpenSSL.', _Reasons.UNSUPPORTED_EXCHA... |
def print_node_balances(chain_state: Any, token_network_address: TokenNetworkAddress, translator: Optional[Translator]=None) -> None:
if (translator is None):
trans = (lambda s: s)
else:
trans = translator.translate
balances = get_node_balances(chain_state, token_network_address)
for bal... |
def old_get_auth(sock, dname, host, dno):
auth_name = auth_data = b''
try:
data = os.popen(('xauth list %s 2>/dev/null' % dname)).read()
lines = data.split('\n')
if (len(lines) >= 1):
parts = lines[0].split(None, 2)
if (len(parts) == 3):
auth_name ... |
def test_new_window(conn):
win = conn.create_window(1, 2, 640, 480)
assert isinstance(win, window.XWindow)
geom = win.get_geometry()
assert (geom.x == 1)
assert (geom.y == 2)
assert (geom.width == 640)
assert (geom.height == 480)
win.kill_client()
with pytest.raises(xcffib.Connection... |
def test_match_benchmark(benchmark, tabbed_browser, qtbot, mode_manager, qapp, config_stub):
tab = tabbed_browser.widget.tabs[0]
with qtbot.wait_signal(tab.load_finished):
tab.load_url(QUrl('qute://testdata/data/hints/benchmark.html'))
config_stub.val.hints.scatter = False
manager = qutebrowser.... |
class UnionType(BaseInstance):
def __init__(self, left: ((UnionType | nodes.ClassDef) | nodes.Const), right: ((UnionType | nodes.ClassDef) | nodes.Const), parent: (nodes.NodeNG | None)=None) -> None:
super().__init__()
self.parent = parent
self.left = left
self.right = right
def ... |
.parametrize('case', ['to_false', 'to_true_free', 'to_true_busy'])
def test_admin_session_update_layout_generation(mock_emit_session_update: MagicMock, clean_database, flask_app, case):
user1 = database.User.create(id=1234, name='The Name')
user2 = database.User.create(id=1235, name='Other')
session = datab... |
class F15_Raid(F14_Raid):
removedKeywords = F14_Raid.removedKeywords
removedAttrs = F14_Raid.removedAttrs
def _getParser(self):
op = F14_Raid._getParser(self)
op.add_argument('--label', version=F15, help='\n Specify the label to give to the filesystem to be made.\n ... |
class TestCliffordGroup():
clifford = gates.qubit_clifford_group()
pauli = [qutip.qeye(2), qutip.sigmax(), qutip.sigmay(), qutip.sigmaz()]
def test_single_qubit_group_dimension_is_24(self):
assert (len(self.clifford) == 24)
def test_all_elements_different(self):
clifford = [_remove_globa... |
def reshape_patch_back(patch_tensor, patch_size):
assert (5 == patch_tensor.ndim)
batch_size = np.shape(patch_tensor)[0]
seq_length = np.shape(patch_tensor)[1]
patch_height = np.shape(patch_tensor)[2]
patch_width = np.shape(patch_tensor)[3]
channels = np.shape(patch_tensor)[4]
img_channels =... |
def test_upload_uuid_in_batches(local_client, remote_client):
records = generate_fixtures(UPLOAD_NUM_VECTORS)
vectors = defaultdict(list)
for record in records:
for (vector_name, vector) in record.vector.items():
vectors[vector_name].append(vector)
batch = models.Batch(ids=[str(uuid.... |
def test_size_hint(view):
view.show_message(message.MessageInfo(usertypes.MessageLevel.info, 'test1'))
height1 = view.sizeHint().height()
assert (height1 > 0)
view.show_message(message.MessageInfo(usertypes.MessageLevel.info, 'test2'))
height2 = view.sizeHint().height()
assert (height2 == (heigh... |
def list_longest_drawdowns(prices_tms: QFSeries, count: int) -> List[Tuple[(datetime, datetime)]]:
result = []
drawdown_timeseries = drawdown_tms(prices_tms)
start_date = None
for (date, value) in drawdown_timeseries.iteritems():
if (value == 0):
if (start_date is not None):
... |
.requires_user_action
class ContentValignTestCase(InteractiveTestCase):
def test_content_valign_bottom(self):
self.window = TestWindow(resizable=True, visible=False, content_valign='bottom')
self.window.set_visible()
app.run()
self.user_verify('Test passed?', take_screenshot=False)
... |
def inference_segmentor(model, img):
cfg = model.cfg
device = next(model.parameters()).device
test_pipeline = ([LoadImage()] + cfg.data.test.pipeline[1:])
test_pipeline = Compose(test_pipeline)
data = dict(img=img)
data = test_pipeline(data)
data = collate([data], samples_per_gpu=1)
if n... |
def test_config_file(tmp_path):
config_body = '\n exec_before = "from collections import Counter as C"\n '
config_file_path = (tmp_path / 'config.toml')
config_file_path.write_text(config_body)
args = ['apply', 'C(x)']
stdin = '1\n2\n'.encode()
env = dict(os.environ)
env.update({f'{uti... |
def recv_batch(batch_queue, replay_ip, device):
def _thunk(thread_queue):
ctx = zmq.Context.instance()
socket = ctx.socket(zmq.DEALER)
socket.setsockopt(zmq.IDENTITY, pickle.dumps('dealer-{}'.format(os.getpid())))
socket.connect('tcp://{}:51003'.format(replay_ip))
outstanding... |
def get_exp_subspace(fea_weight_lst, w2s_ratio, real_exp_len=None):
exp_subspace_lst = []
n_ano = len(fea_weight_lst)
dim = len(fea_weight_lst[0])
for ii in range(n_ano):
fea_weight = fea_weight_lst[ii]
if (w2s_ratio == 'real_len'):
if (real_exp_len is None):
... |
_cache(maxsize=1000, typed=False)
def get_column_picklist(table_name: str, column_name: str, db_path: str) -> list:
fetch_sql = 'SELECT DISTINCT `{}` FROM `{}`'.format(column_name, table_name)
try:
conn = sqlite3.connect(db_path, uri=True)
conn.text_factory = bytes
c = conn.cursor()
... |
class _TensorDictKeysView():
def __init__(self, tensordict: T, include_nested: bool, leaves_only: bool, is_leaf: Callable[([Type], bool)]=None) -> None:
self.tensordict = tensordict
self.include_nested = include_nested
self.leaves_only = leaves_only
if (is_leaf is None):
... |
class MongoLogger(FlaggingCallback):
def __init__(self, url, project_name) -> None:
self.url = url
self.client = MongoClient(url)
self.project_name = project_name
self.components = None
self.db = None
try:
self.client.admin.command('ping')
prin... |
class MishActivation(nn.Module):
def __init__(self):
super().__init__()
if (version.parse(torch.__version__) < version.parse('1.9.0')):
self.act = self._mish_python
else:
self.act = nn.functional.mish
def _mish_python(self, input: Tensor) -> Tensor:
return... |
def feedforwardGAN(qnnArch, unitaries, inputData):
storedStates = []
for x in range(len(inputData)):
currentState = (inputData[x] * inputData[x].dag())
layerwiseList = [currentState]
for l in range(1, len(qnnArch)):
currentState = makeLayerChannel(qnnArch, unitaries, l, curre... |
class HeadphoneMonitor(GObject.Object):
__gsignals__ = {'action': (GObject.SignalFlags.RUN_LAST, None, (object,))}
def __init__(self):
super().__init__()
self._subscribe_id = None
self._process = None
self._status = None
def is_connected(self):
if (self._status is Non... |
def _parse_start_and_end_idx(target_nodes: str, num_nodes: int) -> Tuple[(int, int)]:
indices = target_nodes.split(':')
if (len(indices) == 1):
return (int(indices[0]), int(indices[0]))
else:
start_idx = indices[0]
end_idx = indices[1]
return (int((start_idx or '0')), int((en... |
def downgrade(op, tables, tester):
op.create_index('queueitem_retries_remaining', 'queueitem', ['retries_remaining'], unique=False)
op.create_index('queueitem_processing_expires', 'queueitem', ['processing_expires'], unique=False)
op.create_index('queueitem_available_after', 'queueitem', ['available_after']... |
class MultiProcess():
def __init__(self, dataset=None, wiki5m_alias2qid=None, wiki5m_qid2alias=None, head_cluster=None):
self.dataset = dataset
self.wiki5m_alias2qid = wiki5m_alias2qid
self.wiki5m_qid2alias = wiki5m_qid2alias
self.head_cluster = head_cluster
self.output_folde... |
class TestDriverFCIDumpDumpH2(QiskitChemistryTestCase, BaseTestDriverFCIDumpDumper):
def setUp(self):
super().setUp()
self.core_energy = 0.7199
self.num_orbitals = 2
self.num_electrons = 2
self.spin_number = 0
self.wf_symmetry = 1
self.orb_symmetries = [1, 1]
... |
def convert_examples_to_image_features(examples: List[UDInputExample], label_list: List[str], max_seq_length: int, processor: Union[(PyGameTextRenderer, PangoCairoTextRenderer)], transforms: Optional[Callable]=None, pad_token=(- 100), *kwargs) -> Tuple[(List[Dict[(str, Union[(int, torch.Tensor)])]], int)]:
label_ma... |
def read_task_data(task, subgoal_idx=None):
repeat_idx = task['repeat_idx']
task_dict = {'repeat_idx': repeat_idx, 'type': task['task_type'], 'task': '/'.join(task['root'].split('/')[(- 3):(- 1)])}
if (subgoal_idx is not None):
task_dict['subgoal_idx'] = subgoal_idx
task_dict['subgoal_action... |
def synthesis(args):
model = create_model(args)
if (args.resume is not None):
attempt_to_restore(model, args.resume, args.use_cuda)
device = torch.device(('cuda' if args.use_cuda else 'cpu'))
model.to(device)
output_dir = 'samples'
os.makedirs(output_dir, exist_ok=True)
avg_rtf = []
... |
def dqn_heatmap():
from dqn import Net
(x_pxl, y_pxl) = (300, 400)
state = torch.Tensor([[np.cos(theta), np.sin(theta), thetadot] for thetadot in np.linspace((- 8), 8, y_pxl) for theta in np.linspace((- np.pi), np.pi, x_pxl)])
net = Net()
net.load_state_dict(torch.load('param/dqn_net_params.pkl'))
... |
def CopyTo(desc, src, dest):
import win32api, win32con
while 1:
try:
win32api.CopyFile(src, dest, 0)
return
except win32api.error as details:
if (details.winerror == 5):
raise
if silent:
raise
tb = None
... |
def bngl_import_compare_nfsim(bng_file):
m = model_from_bngl(bng_file)
BNG_SEED = 123
with BngFileInterface(model=None) as bng:
bng.action('readFile', file=bng_file, skip_actions=1)
bng.action('simulate', method='nf', n_steps=10, t_end=100, seed=BNG_SEED)
bng.execute()
yfull1... |
class CNN_Parrallel(nn.Module):
def __init__(self):
super(CNN_Parrallel, self).__init__()
self.encoder_1 = CNN_encoder()
self.encoder_2 = CNN_encoder()
self.classifier = nn.Sequential(nn.Linear(((96 * 4) * 6), 128), nn.ReLU(), nn.Linear(128, 14))
def forward(self, x1, x2, flag='u... |
def strip_docstrings(line_gen):
res = []
prev_toktype = token.INDENT
last_lineno = (- 1)
last_col = 0
tokgen = tokenize.generate_tokens(line_gen)
for (toktype, ttext, (slineno, scol), (elineno, ecol), ltext) in tokgen:
if (slineno > last_lineno):
last_col = 0
if (scol... |
class BuildBackbone(object):
def __init__(self, cfgs, is_training):
self.cfgs = cfgs
self.base_network_name = cfgs.NET_NAME
self.is_training = is_training
self.fpn_func = self.fpn_mode(cfgs.FPN_MODE)
self.pretrain_zoo = PretrainModelZoo()
def fpn_mode(self, fpn_mode):
... |
class TFAuto():
def __init__(self, train_data_path, test_data_path, path_root='/tfx'):
self._tfx_root = os.path.join(os.getcwd(), path_root)
self._pipeline_root = os.path.join(self._tfx_root, 'pipelines')
self._metadata_db_root = os.path.join(self._tfx_root, 'metadata.db')
self._meta... |
def test_run_shortcut_minimal_fallback_func_args(mock_pipe, monkeypatch):
shortcuts = {'arb pipe': {'pipeline_name': 'sc pipe'}}
monkeypatch.setattr('pypyr.config.config.shortcuts', shortcuts)
out = run(pipeline_name='arb pipe', args_in=['arb', 'context', 'input'], parse_args=True, dict_in={'a': 'b', 'e': '... |
class PolyConv(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, padding, num_blocks):
super(PolyConv, self).__init__()
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=False)
... |
def opdm_to_ohdm_mapping(dim: int) -> DualBasis:
dbe_list = []
for i in range(dim):
for j in range(i, dim):
dbe = DualBasisElement()
if (i != j):
dbe.add_element('ck', (i, j), 0.5)
dbe.add_element('ck', (j, i), 0.5)
dbe.add_element(... |
def hex_char_dump(strg, ofs, dlen, base=0, fout=sys.stdout, unnumbered=False):
endpos = min((ofs + dlen), len(strg))
pos = ofs
numbered = (not unnumbered)
num_prefix = ''
while (pos < endpos):
endsub = min((pos + 16), endpos)
substrg = strg[pos:endsub]
lensub = (endsub - pos)... |
def test_issue2353(caplog, path_rgb_byte_tif):
from rasterio.warp import calculate_default_transform
with caplog.at_level(logging.INFO):
with rasterio.open(path_rgb_byte_tif) as src:
_ = src.colorinterp
(t, w, h) = calculate_default_transform('PROJCS["unknown",GEOGCS["unknown",DA... |
def wait_for_block(raiden: 'RaidenService', block_number: BlockNumber, retry_timeout: float) -> None:
current = raiden.get_block_number()
log_details = {'node': to_checksum_address(raiden.address), 'target_block_number': block_number}
while (current < block_number):
assert raiden, ALARM_TASK_ERROR_M... |
class DecoderConfigDescriptor(BaseDescriptor):
TAG = 4
decSpecificInfo = None
def __init__(self, fileobj, length):
r = BitReader(fileobj)
try:
self.objectTypeIndication = r.bits(8)
self.streamType = r.bits(6)
self.upStream = r.bits(1)
self.rese... |
class EnumExactValueProvider(BaseEnumProvider):
def _provide_loader(self, mediator: Mediator, request: LoaderRequest) -> Loader:
return self._make_loader(get_type_from_request(request))
def _make_loader(self, enum):
variants = [case.value for case in enum]
value_to_member = self._get_exa... |
.parametrize('setting,expected_value', [(None, None), ('auto', None), ('always', True), ('never', False)])
def test_color_cli_option(runner, setting, expected_value, boxed_context, in_tmp_dir, tmp_path):
args = ['--schemafile', 'schema.json', 'foo.json']
if setting:
args.extend(('--color', setting))
... |
class MyHTTPServer(HTTPServer):
def __init__(self, ghost, *args, **kwargs):
self.ghost = ghost
self.error = None
self.didPrintStartMsg = False
try:
HTTPServer.__init__(self, *args, **kwargs)
except Exception as e:
self.error = e
def service_actions... |
class FastFashionMNIST(datasets.FashionMNIST):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.data = self.data.unsqueeze(1).float().div(255)
self.data = self.data.sub_(0.2861).div_(0.353)
(self.data, self.targets) = (self.data.to('cuda'), self.targets.to(... |
def test_base_head():
head = ExampleHead(3, 400, dict(type='CrossEntropyLoss'))
cls_scores = torch.rand((3, 4))
gt_labels = torch.LongTensor(([2] * 3)).squeeze()
losses = head.loss(cls_scores, gt_labels)
assert ('loss_cls' in losses.keys())
assert (losses.get('loss_cls') > 0), 'cls loss should b... |
.parametrize('parser, expected_error_msg', [(('precondition-unknown-scenario',), "Cannot import precondition scenario 'Unknown Scenario' from feature"), (('precondition-unknown-scenario-same-feature',), "Cannot import precondition scenario 'Unknown Scenario' from feature"), (('precondition-recursion',), 'Your feature')... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.