code stringlengths 281 23.7M |
|---|
.parametrize(('use_ci', 'expected_message'), ((True, f"- AssertionError: {('this_failed' * 100)}"), (False, '- AssertionError: this_failedt...')), ids=('on CI', 'not on CI'))
def test_fail_extra_reporting(pytester: Pytester, monkeypatch, use_ci: bool, expected_message: str) -> None:
if use_ci:
monkeypatch.s... |
class MemEffAttention(Attention):
def forward(self, x: Tensor, attn_bias=None) -> Tensor:
if (not XFORMERS_AVAILABLE):
assert (attn_bias is None), 'xFormers is required for nested tensors usage'
return super().forward(x)
(B, N, C) = x.shape
qkv = self.qkv(x).reshape(B... |
def setUpModule():
global cell, myadc, kadc
cell = gto.Cell()
cell.build(a='\n 0.000000 1.783500 1.783500\n 1.783500 0.000000 1.783500\n 1.783500 1.783500 0.000000\n ', atom='C 1.337625 1.337625 1.337625; C 2.229375 2.229375 2.229375', verbose=... |
def scan_tqdm(n: int, message: typing.Optional[str]=None) -> typing.Callable:
(_update_progress_bar, close_tqdm) = build_tqdm(n, message)
def _scan_tqdm(func):
def wrapper_progress_bar(carry, x):
if (type(x) is tuple):
(iter_num, *_) = x
else:
iter... |
def test_adding_nonwrappers_trylast3(hc: HookCaller, addmeth: AddMeth) -> None:
()
def he_method1_a() -> None:
pass
(trylast=True)
def he_method1_b() -> None:
pass
()
def he_method1_c() -> None:
pass
(trylast=True)
def he_method1_d() -> None:
pass
asse... |
class PixelNormLayer(nn.Module):
def __init__(self, eps=1e-08):
super(PixelNormLayer, self).__init__()
self.eps = eps
def forward(self, x):
return (x / torch.sqrt((torch.mean((x ** 2), dim=1, keepdim=True) + 1e-08)))
def __repr__(self):
return (self.__class__.__name__ + ('(ep... |
class Solution(object):
def isBalanced(self, root):
if (root is None):
return True
if (self.getDepth(root) < 0):
return False
return True
def getDepth(self, node):
if (node is None):
return 1
ld = self.getDepth(node.left)
if (ld... |
_train('inference-only')
def inference_only(loggers, loaders, model, optimizer=None, scheduler=None):
num_splits = len(loggers)
split_names = ['train', 'val', 'test']
perf = [[] for _ in range(num_splits)]
cur_epoch = 0
start_time = time.perf_counter()
for i in range(0, num_splits):
eval... |
def test_create_user_successful(settings, requests_mock):
settings.PLAIN_API = '
requests_mock.post(settings.PLAIN_API, json={'data': {'upsertCustomer': {'result': 'UPDATED', 'customer': {'id': 'c_ABC25904A1DA4E0AF2'}, 'error': None}}})
user = UserFactory(name='Ester', full_name='Ester', email='', username=... |
class TrajectoryReplayPool(ReplayPool):
def __init__(self, observation_space, action_space, max_size):
super(TrajectoryReplayPool, self).__init__()
max_size = int(max_size)
self._max_size = max_size
self._trajectories = deque(maxlen=max_size)
self._trajectory_lengths = deque(... |
def main(seed: int=0, method: str='exact', batch_size: int=100, n_batch: int=200, num_init: int=200, dtype: str='double', output: str=None, problem: str=None, acqf: str='ts', use_full: bool=False, num_inducing: int=500, loss: str='pll', tree_depth: int=4, dim: int=30):
dtype = (torch.double if (dtype == 'double') e... |
def aes_decrypt(word, key=config.aes_key, iv=None, input='base64', padding=True, padding_style='pkcs7', mode=AES.MODE_CBC, no_packb=False):
if ((iv is None) and (not no_packb)):
(word, iv) = umsgpack.unpackb(word)
if no_packb:
input = input.lower()
if (input == 'base64'):
wor... |
def test_swipe_corner_case():
def __test(x, fs, hopsize, otype):
pysptk.swipe(x, fs, hopsize, otype=otype)
np.random.seed(98765)
fs = 16000
x = np.random.rand(16000)
with pytest.raises(ValueError):
__test(x, fs, 80, (- 1))
with pytest.raises(ValueError):
__test(x, fs, 80,... |
def _set_partitions(collection):
collection = list(collection)
if (not collection):
return
if (len(collection) == 1):
(yield [collection])
return
first = collection[0]
for smaller in set_partitions(collection[1:]):
for (n, subset) in enumerate(smaller):
(y... |
class CaptureLastExpression(ast.NodeTransformer):
def __init__(self, tree: ast.AST, *args, **kwargs):
super().__init__(*args, **kwargs)
self.tree = tree
self.last_node = list(ast.iter_child_nodes(tree))[(- 1)]
def visit_Expr(self, node: ast.Expr) -> (ast.Expr | ast.Assign):
if (n... |
class PreSeparableConv2d(nn.Module):
def __init__(self, in_chs, out_chs, kernel_size=3, stride=1, dilation=1, padding='', act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d, first_act=True):
super(PreSeparableConv2d, self).__init__()
norm_act_layer = get_norm_act_layer(norm_layer, act_layer=act_layer)
... |
.usefixtures('include_test_etc')
class TestSceneResampling():
def _fake_resample_dataset(self, dataset, dest_area, **kwargs):
return dataset.copy()
def _fake_resample_dataset_force_20x20(self, dataset, dest_area, **kwargs):
data = np.zeros((20, 20))
attrs = dataset.attrs.copy()
a... |
class FreeFormatLine(Block):
def deserialize_values(cls, line, version_dialect):
format = cls.format(version_dialect)
values = line.split(None, (len(format) - 1))
values_weeded = []
for (x, v) in zip(format, values):
if isinstance(x, bytes):
if (v.upper() ... |
class CompositeMetricAggregator(SupportsCompositeMetricAggregation):
def __init__(self, reduce_mode: ReduceMode=ReduceMode.SUM):
if (reduce_mode not in set(ReduceMode)):
raise ValueError(f'Reduce mode {reduce_mode} not implemented.')
self.reduce_mode = reduce_mode
def aggregate_scene... |
class TestPluginManager(unittest.TestCase):
def setUp(self):
self.pm = qiime2.sdk.PluginManager()
self.plugin = get_dummy_plugin()
self.other_plugin = self.pm.plugins['other-plugin']
def test_plugins(self):
plugins = self.pm.plugins
exp = {'dummy-plugin': self.plugin, 'ot... |
class EventPluginHandler(PluginHandler):
def __init__(self, librarian=None, player=None, songlist=None):
if librarian:
sigs = _map_signals(librarian, blacklist=('notify',))
for (event, _handle) in sigs:
def handler(librarian, *args):
self.__invoke(... |
def test_dsl_async_cmd_run_save_with_stdout():
context = Context({'cmds': {'run': ['A', 'B'], 'save': True, 'stdout': '/arb1'}})
with pytest.raises(ContextError) as err:
AsyncCmdStep('blah', context)
assert (str(err.value) == "You can't set `stdout` or `stderr` when `save` is True.") |
_ignore_inferred
def _follow_pyname(assignment, pymodule, lineno=None):
assign_node = (assignment.type_hint or assignment.ast_node)
if (lineno is None):
lineno = _get_lineno_for_node(assign_node)
holding_scope = pymodule.get_scope().get_inner_scope_for_line(lineno)
pyname = evaluate.eval_node(ho... |
class DeTTECTEditor():
def __init__(self, port):
signal.signal(signal.SIGTERM, self._signal_handler)
signal.signal(signal.SIGINT, self._signal_handler)
self.port = port
self. = None
def _signal_handler(self, signal, frame):
print('Shutting down webserver')
self.
... |
def parse_bdist_wininst(name):
lower = name.lower()
(base, py_ver, plat) = (None, None, None)
if lower.endswith('.exe'):
if lower.endswith('.win32.exe'):
base = name[:(- 10)]
plat = 'win32'
elif lower.startswith('.win32-py', (- 16)):
py_ver = name[(- 7):(-... |
def test_assert_key_is_truthy_key_not_there():
with pytest.raises(KeyNotInContextError) as err:
asserts.assert_key_is_truthy(obj={'k1': None}, key='k2', caller='arb caller', parent='parent name')
assert (str(err.value) == "context['parent name']['k2'] doesn't exist. It must exist for arb caller.") |
.gdalbin
def test_set_nodata(tmpdir):
dst_path = str(tmpdir.join('lol.tif'))
with rasterio.open('tests/data/RGB.byte.tif') as src:
meta = src.meta
meta['nodata'] = 42
with rasterio.open(dst_path, 'w', **meta) as dst:
assert (dst.nodata == 42)
assert (dst.meta['nod... |
def init_logging():
global LOGGER
if (not os.path.isfile(os.path.join(CONFIG_PATH, LOGGING_CONFIG_FILE))):
print('Copying default logging config file...')
try:
shutil.copy2(os.path.join(SAMPLES_PATH, LOGGING_CONFIG_FILE), CONFIG_PATH)
except IOError as error:
prin... |
class Effect3343(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Medium Projectile Turret')), 'falloff', ship.getModifiedItemAttr('eliteBonusHeavyInterdictors1'), skill='Heavy Interdiction Cruise... |
class POPM(Frame):
_framespec = [Latin1TextSpec('email'), ByteSpec('rating', default=0)]
_optionalspec = [IntegerSpec('count', default=0)]
def HashKey(self):
return ('%s:%s' % (self.FrameID, self.email))
def __eq__(self, other):
return (self.rating == other)
__hash__ = Frame.__hash__... |
def add_params_from_parameter_sharding(fused_params: Optional[Dict[(str, Any)]], parameter_sharding: ParameterSharding) -> Dict[(str, Any)]:
if (fused_params is None):
fused_params = {}
if (parameter_sharding.cache_params is not None):
cache_params = parameter_sharding.cache_params
if (c... |
.route('/profile/')
def profile() -> None:
user_data = plugin.client('user').get()['user']
reg_date = date.fromtimestamp(user_data['reg_date'])
dialog = xbmcgui.Dialog()
message = f'''{localize(32035)}: [B]{user_data['username']}[/B]
{localize(32036)}: [B]{reg_date:%d.%m.%Y}[/B]
{localize(32037)}: [B]{i... |
class ZipReader(object):
zip_bank = dict()
def __init__(self):
super(ZipReader, self).__init__()
def get_zipfile(path):
zip_bank = ZipReader.zip_bank
if (path not in zip_bank):
zfile = zipfile.ZipFile(path, 'r')
zip_bank[path] = zfile
return zip_bank[p... |
def batch_dijkstra(slices, sliced_edges, sliced_adjacency_logits, sliced_weight_logits, initial_vertices, target_vertices, *, k_nearest, max_length, max_length_nearest=None, max_steps=None, deterministic=False, presample_edges=False, soft=False, n_jobs=None, validate=True, **kwargs):
n_jobs = (n_jobs or cpu_count()... |
def build_benchmark_googlesheet_payload(config):
data = config.copy()
data['hostname'] = socket.gethostname()
QUERY_NUM = get_query_number()
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
query_time = _get_benchmarked_method_time(filename='benchmarked_main.csv', query_start_time=config.... |
def find_editor():
for var in ('GIT_EDITOR', 'EDITOR'):
editor = os.environ.get(var)
if (editor is not None):
return editor
if (sys.platform == 'win32'):
fallbacks = ['notepad.exe']
else:
fallbacks = ['/etc/alternatives/editor', 'nano']
for fallback in fallbac... |
class TestInferShape(utt.InferShapeTester):
def test_Mean(self):
adtens3 = dtensor3()
adtens3_val = random(3, 4, 5)
aiscal_val = 2
self._compile_and_check([adtens3], [Mean(None)(adtens3)], [adtens3_val], Mean)
self._compile_and_check([adtens3], [Mean(aiscal_val)(adtens3)], [a... |
def linear_matmul(inputs, weight):
hid_dim = weight.get_shape().as_list()[0]
origin_shape = inputs.get_shape().as_list()
inputs = tf.reshape(inputs, [(- 1), hid_dim])
outputs = tf.matmul(inputs, weight)
outputs = tf.reshape(outputs, (origin_shape[:(- 1)] + [(- 1)]))
return outputs |
class TestWheelSource():
def test_takes_two_arguments(self):
WheelSource('distribution', 'version')
WheelSource(distribution='distribution', version='version')
def test_correctly_computes_properties(self):
source = WheelSource(distribution='distribution', version='version')
asser... |
def generate_case_ids(alltests):
import random
for c in alltests:
if (c['id'] == ''):
while True:
newid = str('{:04x}'.format(random.randrange((16 ** 4))))
if does_id_exist(alltests, newid):
continue
else:
... |
.skipif((K.backend() != 'tensorflow'), reason='sparse operations supported only by TF')
_test
def test_sparse_input_validation_split():
test_input = sparse.random(6, 3, density=0.25).tocsr()
in1 = Input(shape=(3,), sparse=True)
out1 = Dense(4)(in1)
test_output = np.random.random((6, 4))
model = Mode... |
def fdr(pvals, alpha=0.05, method='fdr_bh'):
assert (method.lower() in ['fdr_bh', 'fdr_by'])
pvals = np.asarray(pvals)
shape_init = pvals.shape
pvals = pvals.ravel()
num_nan = np.isnan(pvals).sum()
pvals_sortind = np.argsort(pvals)
pvals_sorted = pvals[pvals_sortind]
sortrevind = pvals_s... |
def test_nested():
a = m.NestA()
b = m.NestB()
c = m.NestC()
a += 10
assert (m.get_NestA(a) == 13)
b.a += 100
assert (m.get_NestA(b.a) == 103)
c.b.a += 1000
assert (m.get_NestA(c.b.a) == 1003)
b -= 1
assert (m.get_NestB(b) == 3)
c.b -= 3
assert (m.get_NestB(c.b) == 1)... |
def _make_certbuilder(private_key):
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, 'example.org')])
return x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(private_key.public_key()).serial_number(777).not_valid_before(datetime.datetime(1999, 1, 1)).not_valid_after(datetime.da... |
.parametrize('X_args, Y_args, Z_args, p_val, comp_size, idx_size, extra_indices, join_axis, supported', [((np.array(0, dtype=pytensor.config.floatX), np.array(1, dtype=pytensor.config.floatX)), (np.array(0.5, dtype=pytensor.config.floatX), np.array(2.0, dtype=pytensor.config.floatX)), (np.array(100, dtype=pytensor.conf... |
def weights_init_orthogonal(m):
classname = m.__class__.__name__
if (classname.find('Conv') != (- 1)):
init.orthogonal(m.weight.data, gain=1)
elif (classname.find('Linear') != (- 1)):
init.orthogonal(m.weight.data, gain=1)
elif (classname.find('BatchNorm') != (- 1)):
init.normal(... |
.parametrize('p_val, size, supported', [(np.array(0.0, dtype=pytensor.config.floatX), (), True), (np.array(1.0, dtype=pytensor.config.floatX), (), True), (np.array([0.1, 0.9], dtype=pytensor.config.floatX), (), True), (np.array(0.0, dtype=pytensor.config.floatX), (2,), False), (np.array(1.0, dtype=pytensor.config.float... |
class ResNet50vd_dcn(nn.Module):
def __init__(self, cout=64, idx=0):
super(ResNet50vd_dcn, self).__init__()
self.cout = cout
self.idx = idx
self.resnet50vd_dcn = ResNet(channels=[64, 128, 256, 512], cout=cout, idx=idx, block=Bottleneck, layers=layers, stem_width=32, stem_type='deep',... |
def test_bose_hubbard_2x2_aperiodic():
hubbard_model = bose_hubbard(2, 2, 1.0, 4.0, chemical_potential=0.5, dipole=0.3, periodic=False)
assert (str(hubbard_model).strip() == '\n-1.0 [0 1^] +\n-1.0 [0 2^] +\n-2.5 [0^ 0] +\n2.0 [0^ 0 0^ 0] +\n0.3 [0^ 0 1^ 1] +\n0.3 [0^ 0 2^ 2] +\n-1.0 [0^ 1] +\n-1.0 [0^ 2] +\n-1.... |
def create_identifier(apps, schema_editor):
Catalog = apps.get_model('questions', 'Catalog')
Section = apps.get_model('questions', 'Section')
Subsection = apps.get_model('questions', 'Subsection')
QuestionEntity = apps.get_model('questions', 'QuestionEntity')
for obj in Catalog.objects.all():
... |
class PlayWorldBorder(Packet):
id = 61
to = 1
def __init__(self, action: int, data: dict) -> None:
super().__init__()
self.action = action
self.data = data
def encode(self) -> bytes:
out = Buffer.pack_varint(self.action)
if (self.action == 0):
out += B... |
def test_process_queries_full_query(cortex_product: CortexXDR, mocker):
cortex_product._queries = {}
cortex_product._results = {}
cortex_product._url = '
mocker.patch('products.cortex_xdr.CortexXDR._get_default_header', return_value={})
criteria = {'query': ['FieldA=cmd.exe']}
cortex_product.nes... |
def test_chord_mode_name_deprecation(caplog):
chord = KeyChord([], 'a', [Key([], 'b', lazy.function(no_op))], mode='persistent_chord')
assert caplog.records
log = caplog.records[0]
assert (log.levelname == 'WARNING')
assert ("name='persistent_chord'" in log.message)
assert (chord.mode is True)
... |
def plot_longitudinal_profile_intensity(self, longitudinal_profile_E, extent, square_root=False, grid=False, xlim=None, ylim=None, units=mm, z_units=cm, dark_background=True):
from ..util.backend_functions import backend as bd
if (dark_background == True):
plt.style.use('dark_background')
else:
... |
def test_make_valid_identifier():
assert (make_valid_identifier('has whitespaces ') == 'has_whitespaces')
assert (make_valid_identifier('has-hyphon') == 'has_hyphon')
assert (make_valid_identifier('special chars%') == 'special_chars')
assert (make_valid_identifier('UpperCase') == 'uppercase')
with p... |
class F19_Bootloader(F18_Bootloader):
removedKeywords = F18_Bootloader.removedKeywords
removedAttrs = F18_Bootloader.removedAttrs
def __init__(self, writePriority=10, *args, **kwargs):
F18_Bootloader.__init__(self, writePriority, *args, **kwargs)
self.extlinux = kwargs.get('extlinux', False)... |
class DynamicLossScaler(object):
def __init__(self, init_scale=(2.0 ** 15), scale_factor=2.0, scale_window=2000, tolerance=0.0, threshold=None, min_loss_scale=0.0001):
self.loss_scale = init_scale
self.scale_factor = scale_factor
self.scale_window = scale_window
self.tolerance = tole... |
def test_current_test_env_var(pytester: Pytester, monkeypatch: MonkeyPatch) -> None:
pytest_current_test_vars: List[Tuple[(str, str)]] = []
monkeypatch.setattr(sys, 'pytest_current_test_vars', pytest_current_test_vars, raising=False)
pytester.makepyfile("\n import pytest\n import sys\n ... |
class FastLookup(CompleteDirs):
def namelist(self):
with contextlib.suppress(AttributeError):
return self.__names
self.__names = super(FastLookup, self).namelist()
return self.__names
def _name_set(self):
with contextlib.suppress(AttributeError):
return se... |
def crack(args, s):
s.adapter.set_tclk(1)
s.adapter.set_sclk(127)
code = []
while (len(code) != 7):
logging.info('Cracking byte {}/7...'.format((len(code) + 1), 7))
byte_times = []
for try_byte in range(256):
samples = []
for _ in range(args.samples):
... |
class TaskHandler(object):
def __init__(self):
self.tasks = {}
self.to_save = {}
def load(self):
to_save = False
value = ServerConfig.objects.conf('delayed_tasks', default={})
if isinstance(value, str):
tasks = dbunserialize(value)
else:
ta... |
_cache()
def _get_device_calibration(device_name: str):
processor_id = recirq.get_processor_id_by_device_name(device_name)
if (processor_id is None):
device_obj = recirq.get_device_obj_by_name(device_name)
dummy_graph = ccr.gridqubits_to_graph_device((device_obj.metadata.qubit_set if (device_obj... |
def dropout_slim_model():
inputs = tf.keras.Input(shape=(10, 10, 3))
x = slim.conv2d(inputs, 16, [3, 3])
x = slim.dropout(x, keep_prob=0.6)
x = tf.identity(x)
x = slim.conv2d(x, 8, [2, 2])
x = slim.flatten(x)
outputs = slim.fully_connected(x, num_outputs=10, activation_fn=tf.nn.softmax, scop... |
class VolatilityVolumeShareTestCase(WithCreateBarData, WithSimParams, WithDataPortal, ZiplineTestCase):
ASSET_START_DATE = pd.Timestamp('2006-02-10')
TRADING_CALENDAR_STRS = ('NYSE', 'us_futures')
TRADING_CALENDAR_PRIMARY_CAL = 'us_futures'
def init_class_fixtures(cls):
super(VolatilityVolumeSha... |
_start_docstrings('\n ConvNext Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ', CONVNEXT_START_DOCSTRING)
class TFConvNextForImageClassification(TFConvNextPreTrainedModel, TFSequenceClassificationLoss):
def __init__(self, config: ConvN... |
class TestCopyPlane(EndianTest):
def setUp(self):
self.req_args_0 = {'bit_plane': , 'dst_drawable': , 'dst_x': (- 25480), 'dst_y': (- 26229), 'gc': , 'height': 60447, 'src_drawable': , 'src_x': (- 4634), 'src_y': (- 17345), 'width': 53771}
self.req_bin_0 = b'?\x00\x08\x00\x8d \xf80H)\xa4o\x85\xed\xf... |
def test_unrecognised_optional_parameters():
client = Client('localhost', 5679)
pdu = DeliverSM('deliver_sm', client=client, allow_unknown_opt_params=True)
pdu.parse(b'\x00\x00\x00\xa8\x00\x00\x00\x05\x00\x00\x00\x00/p\xc6\x9a\x00\x00\x\x00\x01\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00iid: sub:001 dlvrd:0... |
def test_instance_method() -> None:
nodes_ = builder.extract_node('\n class A:\n def method(self, x):\n return x\n\n A().method(42) #\n\n # In this case, the 1 argument is bound to self, which is ignored in the method\n A.method(1, 42) #\n ')
for node in nodes_:
assert... |
class TestNanPayloads(unittest.TestCase):
def test_normal_nan(self):
normal_nan = float('nan')
(payload, namespace) = get_payload_from_nan(normal_nan)
self.assertIs(payload, None)
self.assertIs(namespace, None)
def test_roundtrip_payload(self):
for namespace in range(0, 2... |
.parametrize('run_parameters, expected_error, expected_message', [({}, None, None), ({'refs': {'kind': 'branch', 'name': 'invalid'}}, TriggerStartException, 'Could not find branch in repository'), ({'refs': {'kind': 'tag', 'name': 'invalid'}}, TriggerStartException, 'Could not find tag in repository'), ({'refs': {'kind... |
def _read_quadrangle_annotations(csv_reader, classes, detect_text=False):
result = OrderedDict()
for (line, row) in enumerate(csv_reader, 1):
try:
(img_file, x1, y1, x2, y2, x3, y3, x4, y4, class_name) = row[:10]
if (img_file not in result):
result[img_file] = []
... |
def get_queries_from_constant_and_query(constant_smiles, query_smiles):
num_constant_attachments = constant_smiles.count('*')
num_query_attachments = query_smiles.count('*')
if (num_constant_attachments != num_query_attachments):
raise click.UsageError(f'Mismatch between the number of attachment poi... |
class _MarkerFinder():
def __init__(self, stream):
super(_MarkerFinder, self).__init__()
self._stream = stream
def from_stream(cls, stream):
return cls(stream)
def next(self, start):
position = start
while True:
position = self._offset_of_next_ff_byte(star... |
.parametrize('parse_pattern, string, expected_args, expected_kwargs', [('Given I have the number {:d}', 'Given I have the number 5', (5,), {}), ('Given I have the number {number:d}', 'Given I have the number 5', tuple(), {'number': 5}), ('Given I have the number {number:d} and {:d}', 'Given I have the number 4 and 2', ... |
class BloombergDataLicenseTypeConverter():
def infer_type(self, series: QFSeries, bbg_data_type: str) -> QFSeries:
field_types = {'String': self._string_conversion, 'Character': self._string_conversion, 'Long Character': self._string_conversion, 'Date or Time': self._date_conversion, 'Integer': self._float_... |
class OSM_strategy(Policy):
def __init__(self, observation_space, action_space, config):
Policy.__init__(self, observation_space, action_space, config)
self.osm = OSM(config['alpha'], config['gamma'], config['blocks'])
self.osm.MDP_matrix_init()
(P, R) = self.osm.get_MDP_matrix()
... |
def desktop_set_B3():
global REQUIRE_REBOOT
sp.call(shlex.split('systemctl set-default graphical.target'))
if os.path.isfile('/etc/systemd/system/getty.target.wants/.service'):
os.remove('/etc/systemd/system/getty.target.wants/.service')
os.symlink('/lib/systemd/system//etc/systemd/system/getty.... |
class Regex(Token):
def __init__(self, pattern: Any, flags: Union[(re.RegexFlag, int)]=0, as_group_list: bool=False, as_match: bool=False, *, asGroupList: bool=False, asMatch: bool=False):
super().__init__()
asGroupList = (asGroupList or as_group_list)
asMatch = (asMatch or as_match)
... |
def test_cell_n2(L=5, mesh=([9] * 3)):
cell = pbcgto.Cell()
cell.unit = 'B'
cell.atom.extend([['O', ((L / 2.0), (L / 2.0), (L / 2.0))], ['H', (((L / 2.0) - 0.68944), ((L / 2.0) + 0.578509), (L / 2.0))], ['H', (((L / 2.0) + 0.68944), ((L / 2.0) - 0.578509), (L / 2.0))]])
cell.a = (L * np.identity(3))
... |
class JobTelecommute(JobLocationMenu, JobList):
template_name = 'jobs/job_telecommute_list.html'
def get_queryset(self):
return super().get_queryset().visible().select_related().filter(telecommuting=True)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
... |
def ensemble_models(model_paths: List[str], cxr_filepath: str, cxr_labels: List[str], cxr_pair_template: Tuple[str], cache_dir: str=None, save_name: str=None) -> Tuple[(List[np.ndarray], np.ndarray)]:
predictions = []
model_paths = sorted(model_paths)
for path in model_paths:
model_name = Path(path)... |
def bot_factory(repo='foo/foo', user_token='foo', bot_token=None, bot_class=Bot, ignore_ssl=False, prs=list()):
bot = bot_class(repo=repo, user_token=user_token, bot_token=bot_token, ignore_ssl=ignore_ssl)
bot._fetched_prs = True
bot.req_bundle.pull_requests = prs
bot.provider = Mock()
bot.config.up... |
(netloc='fakegitlab', path='/api/v4/projects/4/repository/tags$')
def project_tags_handler(_, request):
if (not (request.headers.get('Authorization') == 'Bearer foobar')):
return {'status_code': 401}
return {'status_code': 200, 'headers': {'Content-Type': 'application/json'}, 'content': json.dumps([{'na... |
.parametrize('username,password', users)
def test_update(db, client, username, password):
client.login(username=username, password=password)
instances = Catalog.objects.all()
for instance in instances:
catalog_sections = [{'section': section.section.id, 'order': section.order} for section in instanc... |
class Chunker():
def __init__(self, grammar: nltk.RegexpParser):
self.grammar = grammar
def chunk_sentence(self, sentence: str):
pos_tagged_sentence = PosTagger(sentence).pos_tag()
return self.chunk_pos_tagged_sentence(pos_tagged_sentence)
def chunk_pos_tagged_sentence(self, pos_tagg... |
def kernel_feature_creator(data, projection_matrix, is_query):
head_dim = tf.constant(data.shape[(- 1)], dtype=tf.dtypes.float32)
support_dim = tf.constant(projection_matrix.shape[0], dtype=tf.dtypes.float32)
data_normalizer = (1.0 / tf.math.sqrt(tf.math.sqrt(head_dim)))
ratio = (1.0 / tf.math.sqrt(supp... |
def delete_links(cwd: Optional[Union[(Path, str)]]=None, verbose: Optional[bool]=None) -> List[Path]:
if (cwd is None):
cwd = Path.cwd()
elif isinstance(cwd, str):
cwd = Path(cwd)
delete = []
for path in cwd.iterdir():
if path.is_symlink():
delete.append(path)
if ... |
class CompoundLoss(_Loss):
def __init__(self, blocks=[1, 2, 3, 4], mse_weight=1, resnet_weight=0.01):
super(CompoundLoss, self).__init__()
self.mse_weight = mse_weight
self.resnet_weight = resnet_weight
self.blocks = blocks
self.model = ResNet50FeatureExtractor(pretrained=Tru... |
class StopInternalConnectivity(InternalConnectivity):
def forward_propagate_the_masks(self, input_mask_list: List[List[int]], output_mask_list: List[List[int]]) -> bool:
mask_changed = False
return mask_changed
def backward_propagate_the_masks(self, output_mask_list: List[List[int]], input_mask_... |
def add(*args, **kwargs):
if (len(args) > 1):
(val1, val2) = (args[0], args[1])
try:
val1 = literal_eval(val1.strip())
except Exception:
pass
try:
val2 = literal_eval(val2.strip())
except Exception:
pass
return (val1 + v... |
def import_dotted_path(dotted_path: str) -> Callable:
(module_name, component_name) = dotted_path.rsplit('.', 1)
try:
module = import_module(module_name)
except ImportError as error:
raise RuntimeError(f'Failed to import {module_name!r} while loading {component_name!r}') from error
retur... |
def all_gatherv(input, return_boundaries=False):
num_elements = torch.tensor(input.size(0), device=input.device)
num_elements_per_process = all_gather(num_elements, cat=False)
max_elements = num_elements_per_process.max()
difference = (max_elements - input.size(0))
if (difference > 0):
input... |
class Scrim(BaseDbModel):
class Meta():
table = 'sm.scrims'
id = fields.BigIntField(pk=True, index=True)
guild_id = fields.BigIntField()
name = fields.TextField(default='Quotient-Scrims')
registration_channel_id = fields.BigIntField(index=True)
slotlist_channel_id = fields.BigIntField()
... |
class PosAlign(nn.Module):
def __init__(self):
super(PosAlign, self).__init__()
self.soft_plus = nn.Softplus()
def forward(self, feature, target):
feature = F.normalize(feature, p=2, dim=1)
feature = torch.matmul(feature, feature.transpose(1, 0))
label_matrix = (target.un... |
def createFile(finalSize=):
chunk = np.random.normal(size=1000000).astype(np.float32)
f = h5py.File('test.hdf5', 'w')
f.create_dataset('data', data=chunk, chunks=True, maxshape=(None,))
data = f['data']
nChunks = (finalSize // (chunk.size * chunk.itemsize))
with pg.ProgressDialog('Generating tes... |
def assert_dropped(iteration: TransitionResult, old_state: Any, reason: Optional[str]=None):
msg = f"State change expected to be dropped ({(reason or 'reason unknown')})."
assert ((iteration.new_state is None) or (iteration.new_state == old_state)), msg
assert (not iteration.events), msg |
def get_vertices(v, degree_v, degrees, a_vertices):
a_vertices_selected = (2 * math.log(a_vertices, 2))
vertices = deque()
try:
c_v = 0
for v2 in degrees[degree_v]['vertices']:
if (v != v2):
vertices.append(v2)
c_v += 1
if (c_v > a_... |
class MonsterBio(commands.Cog):
def generate_name(self, seeded_random: random.Random) -> str:
n_candidate_strings = seeded_random.randint(2, len(TEXT_OPTIONS['monster_type']))
return ''.join((seeded_random.choice(TEXT_OPTIONS['monster_type'][i]) for i in range(n_candidate_strings)))
(brief='Send... |
def evaluate(result_sha, mail, num_hypo, eval_3diou, eval_2diou, thres):
if eval_3diou:
mail.msg('Processing Result for KITTI 3D MOT Benchmark')
elif eval_2diou:
mail.msg('Processing Result for KITTI 2D MOT Benchmark')
else:
assert False, 'error'
classes = []
for c in ('cycli... |
class ReIDModel():
def __init__(self):
self.model = resnet50(num_classes=751, loss='softmax', pretrained=True, use_gpu=True)
load_pretrained_weights(self.model, config.reid_resnet50_market_weight_path)
self.device = 'cuda'
self.model.to(self.device)
self.model.eval()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.