code stringlengths 281 23.7M |
|---|
def test_while_exec_iteration_stop_evals_true():
wd = WhileDecorator({'stop': '{stop}'})
context = Context({'stop': True})
mock = MagicMock()
assert wd.exec_iteration(2, context, mock)
assert (context['whileCounter'] == 2)
assert (wd.while_counter == 2)
assert (len(context) == 2)
mock.as... |
def run_step(context):
logger.debug('started')
context.assert_key_has_value(key='pathCheck', caller=__name__)
paths_to_check = context['pathCheck']
if (not paths_to_check):
raise KeyInContextHasNoValueError(f"context['pathCheck'] must have a value for {__name__}.")
if isinstance(paths_to_che... |
class DecodedCorpus():
def __init__(self, path_decoded_doc2sents):
self.path_decoded_doc2sents = Path(path_decoded_doc2sents)
self.decoded_doc2sents = utils.Json.load(path_decoded_doc2sents)
def dump_html(self):
path_output = self.path_decoded_doc2sents.with_name(self.path_decoded_doc2se... |
def test():
spi = SPI(1, baudrate=, sck=Pin(14), mosi=Pin(13))
display = Display(spi, dc=Pin(4), cs=Pin(16), rst=Pin(17))
print('Loading fonts...')
print('Loading arcadepix')
arcadepix = XglcdFont('fonts/ArcadePix9x11.c', 9, 11)
print('Loading bally')
bally = XglcdFont('fonts/Bally7x9.c', 7,... |
class Multitask_Iterator_Wrapper():
def __init__(self, multitask_dataloader):
self.multitask_dataloader = multitask_dataloader
self.dataloaders = OrderedDict([(k, iter(x)) for (k, x) in self.multitask_dataloader.items()])
self._index = 0
self.max_n_iters = min([len(x) for (k, x) in s... |
.parametrize('enabled_extra', ['one', 'two', None])
def test_solver_returns_extras_when_multiple_extras_use_same_dependency(solver: Solver, repo: Repository, package: ProjectPackage, enabled_extra: (bool | None)) -> None:
package.add_dependency(Factory.create_dependency('A', '*'))
package_a = get_package('A', '... |
class TestNearestUnequalElements(ZiplineTestCase):
_space(tz=['UTC', 'US/Eastern'], __fail_fast=True)
def test_nearest_unequal_elements(self, tz):
dts = pd.to_datetime(['2014-01-01', '2014-01-05', '2014-01-06', '2014-01-09']).tz_localize(tz)
def t(s):
return (None if (s is None) else... |
class UnBan(ScrimsButton):
def __init__(self):
super().__init__(label='Unban Users', style=discord.ButtonStyle.green)
async def callback(self, interaction: discord.Interaction):
(await interaction.response.defer())
if (not (banned_teams := (await self.view.record.banned_teams.order_by('i... |
def test_set_as_str_things(echoes_resource_database):
item = echoes_resource_database.get_item_by_name
req_set = RequirementSet([RequirementList([ResourceRequirement.simple(item('Screw Attack')), ResourceRequirement.simple(item('Space Jump Boots'))]), RequirementList([ResourceRequirement.simple(item('Power Bomb... |
def _warn_incompatibility_with_xunit2(request: FixtureRequest, fixture_name: str) -> None:
from _pytest.warning_types import PytestWarning
xml = request.config.stash.get(xml_key, None)
if ((xml is not None) and (xml.family not in ('xunit1', 'legacy'))):
request.node.warn(PytestWarning("{fixture_name... |
def test_is_same_crs():
crs1 = CRS({'init': 'epsg:4326'})
crs2 = CRS({'init': 'epsg:3857'})
assert (crs1 == crs1)
assert (crs1 != crs2)
wgs84_crs = CRS.from_string('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
assert (crs1 == wgs84_crs)
lcc_crs1 = CRS.from_string('+lon_0=-95 +ellps=GRS... |
def target_from_node(module: str, node: ((FuncDef | MypyFile) | OverloadedFuncDef)) -> (str | None):
if isinstance(node, MypyFile):
if (module != node.fullname):
return None
return module
elif node.info:
return f'{node.info.fullname}.{node.name}'
else:
return f'{m... |
def init_tokenizer():
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
tokenizer.add_special_tokens({'bos_token': '[DEC]'})
tokenizer.add_special_tokens({'additional_special_tokens': ['[ENC]']})
tokenizer.enc_token_id = tokenizer.additional_special_tokens_ids[0]
return tokenizer |
class MqlLexer(CppLexer):
name = 'MQL'
aliases = ['mql', 'mq4', 'mq5', 'mql4', 'mql5']
filenames = ['*.mq4', '*.mq5', '*.mqh']
mimetypes = ['text/x-mql']
version_added = '2.0'
tokens = {'statements': [(words(_mql_builtins.keywords, suffix='\\b'), Keyword), (words(_mql_builtins.c_types, suffix='\... |
def get_string(prompt, default=None, none_ok=False):
full_prompt = prompt
if default:
full_prompt += ' [{}]'.format(default)
if none_ok:
full_prompt += ' [enter "none" to clear]'
full_prompt += ' '
answer = input(full_prompt)
if (answer == ''):
answer = default
... |
class SARIce(GenericCompositor):
def __call__(self, projectables, *args, **kwargs):
(mhh, mhv) = projectables
ch1attrs = mhh.attrs
ch2attrs = mhv.attrs
mhh = (np.sqrt((mhh + 0.002)) - 0.04)
mhv = (np.sqrt((mhv + 0.002)) - 0.04)
mhh.attrs = ch1attrs
mhv.attrs =... |
(name='i18n-compile')
def i18n_compile(ctx):
env = create_env('build', requirements=True)
dest_dir = os.path.join(BASE, PROJECT, 'i18n')
orig_dir = os.path.join(BASE, 'i18n', 'langs')
os.makedirs(dest_dir, exist_ok=True)
for lang in i18n_available():
invoke.run(('%s/bin/pybabel compile -i %s... |
def login_with_token(client: GMatrixClient, user_id: str, access_token: str) -> Optional[User]:
client.set_access_token(user_id=user_id, token=access_token)
try:
client.api.get_devices()
except MatrixRequestError as ex:
log.debug("Couldn't use previous login credentials", node=node_address_f... |
def run_on_leader(pg: dist.ProcessGroup, rank: int):
def callable(func: Callable[(..., T)]) -> T:
(func)
def wrapped(*args: Any, **kwargs: Any) -> T:
return invoke_on_rank_and_broadcast_result(pg, rank, func, *args, **kwargs)
return wrapped
return callable |
class PaneConfig():
def __init__(self, row_pattern):
parts = [p.replace('\\:', ':') for p in re.split('(?<!\\\\):', row_pattern)]
def is_numeric(s):
return ((s[:2] == '~#') and ('~' not in s[2:]))
def is_pattern(s):
return ('<' in s)
def f_round(s):
... |
class Effect1264(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Small Hybrid Turret')), 'trackingSpeed', ship.getModifiedItemAttr('eliteBonusInterceptor2'), skill='Interceptors', **kwargs) |
class TestWaitForRequest(BaseTestCase):
async def test_wait_for_request(self):
(await self.page.goto((self.url + 'empty')))
results = (await asyncio.gather(self.page.waitForRequest((self.url + 'static/digits/2.png')), self.page.evaluate("() => {\n fetch('/static/digits/1.png');\n ... |
def tokenize_caption(input_json: str, keep_punctuation: bool=False, host_address: str=None, character_level: bool=False, zh: bool=False, output_json: str=None):
data = json.load(open(input_json, 'r'))['audios']
if zh:
from nltk.parse.corenlp import CoreNLPParser
from zhon.hanzi import punctuatio... |
def dsystem_dt(request):
sys = rss(3, 1, 1)
A = [[(- 3.0), 4.0, 2.0], [(- 1.0), (- 3.0), 0.0], [2.0, 5.0, 3.0]]
B = [[1.0, 4.0], [(- 3.0), (- 3.0)], [(- 2.0), 1.0]]
C = [[4.0, 2.0, (- 3.0)], [1.0, 4.0, 3.0]]
D = [[(- 2.0), 4.0], [0.0, 1.0]]
dt = request.param
systems = {'sssiso': StateSpace(... |
def colorForName(name):
list = [('c1', '#ec9999'), ('c2', '#ffc1a6'), ('c3', '#fff0a6'), ('c4', '#adf199'), ('c5', '#9fadea'), ('c6', '#a699c1'), ('c7', '#ad99b4'), ('c8', '#eaffea'), ('c9', '#dcecfb'), ('c10', '#ffffea')]
i = 0
total = 0
count = len(list)
while (i < len(name)):
total += ord... |
def filed_based_convert_examples_to_features(examples, label_list, max_seq_length, tokenizer, output_file):
writer = tf.python_io.TFRecordWriter(output_file)
for (ex_index, example) in enumerate(examples):
if ((ex_index % 10000) == 0):
tf.logging.info(('Writing example %d of %d' % (ex_index,... |
class Scope():
def __init__(self, ctx):
self.ctx = ctx
self._locals = []
self._parent_locals = []
def add_reference(self, ref):
self._locals.append(ref)
def add_parent_reference(self, ref):
new_ref = self.ctx.cache.process_pool.save(ref)
if (self.ctx.cache.nam... |
def read_nyt(id_json):
f = open(id_json, 'r')
ids = f.readlines()
f.close()
print(ids[:2])
f = open(label_f, 'r')
label_vocab_s = f.readlines()
f.close()
label_vocab = []
for label in label_vocab_s:
label = label.strip()
label_vocab.append(label)
id_list = []
... |
.parametrize('dynamic', [False, True])
def test_control_dict_str_map(dynamic):
class Fake(FakeBase):
x = CommonBase.control('', '%d', '', validator=strict_discrete_set, values={'X': 1, 'Y': 2, 'Z': 3}, map_values=True, dynamic=dynamic)
fake = Fake()
fake.x = 'X'
assert (fake.read() == '1')
f... |
class GetPass(object):
def _unix_getch(self):
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
... |
def macos_kernel_api(params: Mapping[(str, Any)]={}, passthru: bool=False):
def decorator(func):
def wrapper(ql: Qiling, pc: int, api_name: str):
onenter = ql.os.user_defined_api[QL_INTERCEPT.ENTER].get(api_name)
onexit = ql.os.user_defined_api[QL_INTERCEPT.EXIT].get(api_name)
... |
def ConvertPatchMatrix(matrix, patch_number):
(h, w) = (matrix.shape[0], matrix.shape[1])
(sub_h, sub_w) = ((h / patch_number), (w / patch_number))
new_matrix = np.zeros((patch_number, patch_number), dtype=float)
for i in range(patch_number):
for j in range(patch_number):
new_matrix[... |
def test_file_remote(testdir):
key = 'goog:chromeOptions'
capabilities = {'browserName': 'chrome', key: {'args': ['foo']}}
variables = testdir.makefile('.json', '{{"capabilities": {}}}'.format(json.dumps(capabilities)))
file_test = testdir.makepyfile("\n import pytest\n .nondestructive\n ... |
def parse_date_or_none(date_string, delta=None, dayfirst=True, **timedelta_kwargs):
if ((not isinstance(date_string, str)) or (not date_string)):
return None
if (delta and (delta not in ('positive', 'negative'))):
raise ValueError("Invalid delta option. Options are 'positive' or 'negative'")
... |
def test_mkdm_simple_repr():
dm = data.mkdm(matrix=[[1, 2, 3], [4, 5, 6], [7, 8, 9]], objectives=[min, max, min], weights=[0.1, 0.2, 0.3])
expected = ' C0[ 0.1] C1[ 0.2] C2[ 0.3]\nA0 1 2 3\nA1 4 5 6\nA2 7 8 9\n[3 Alternatives ... |
def _get_layer_output_shape(layer: tf.keras.layers) -> Tuple:
output_activation_shape = list(layer.output_shape)
if (len(output_activation_shape) == 4):
reorder = [0, 3, 1, 2]
output_activation_shape = [output_activation_shape[idx] for idx in reorder]
if isinstance(layer, tf.keras.layers.Den... |
class TestPollBase():
id_ = 'id'
question = 'Test?'
options = [PollOption('test', 10), PollOption('test2', 11)]
total_voter_count = 0
is_closed = True
is_anonymous = False
type = Poll.REGULAR
allows_multiple_answers = True
explanation = b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f4... |
class TestSlabInfoCollector(CollectorTestCase):
def setUp(self):
config = get_collector_config('SlabInfoCollector', {'interval': 1})
self.collector = SlabInfoCollector(config, None)
def test_import(self):
self.assertTrue(SlabInfoCollector)
('__builtin__.open')
('os.access', Mock(... |
class PdbInvoke():
def pytest_exception_interact(self, node: Node, call: 'CallInfo[Any]', report: BaseReport) -> None:
capman = node.config.pluginmanager.getplugin('capturemanager')
if capman:
capman.suspend_global_capture(in_=True)
(out, err) = capman.read_global_capture()
... |
def coriolis_sideinfo_simple(qp: QP, env_sys: System):
dp_j = env_sys.joint_revolute.apply(qp)
dp_j += env_sys.joint_universal.apply(qp)
dp_j += env_sys.joint_spherical.apply(qp)
dp_vel = (((env_sys.config.velocity_damping * qp.vel) + (dp_j.vel + vec_to_np(env_sys.config.gravity))) * env_sys.active_pos)... |
class CmdCopy(ObjManipCommand):
key = 'copy'
switch_options = ('reset',)
locks = 'cmd:perm(copy) or perm(Builder)'
help_category = 'Building'
def func(self):
caller = self.caller
args = self.args
if (not args):
caller.msg('Usage: copy <obj> [=<new_name>[;alias;ali... |
class ThriftClient(config.Parser):
def __init__(self, client_cls: Any, **kwargs: Any):
self.client_cls = client_cls
self.kwargs = kwargs
def parse(self, key_path: str, raw_config: config.RawConfig) -> ContextFactory:
pool = thrift_pool_from_config(raw_config, prefix=f'{key_path}.', **sel... |
class Plane(Shape):
_p3js_geometry_type = 'Plane'
_p3js_attribute_map = {'width': 'width', 'height': 'length'}
_p3js_material_attributes = {'side': 'DoubleSide'}
def __init__(self, length=10.0, width=5.0, **kwargs):
super(Plane, self).__init__(**kwargs)
self.geometry_attrs += ['length', ... |
class ParaphraseMiningEvaluator(SentenceEvaluator):
def __init__(self, sentences_map: Dict[(str, str)], duplicates_list: List[Tuple[(str, str)]]=None, duplicates_dict: Dict[(str, Dict[(str, bool)])]=None, add_transitive_closure: bool=False, query_chunk_size: int=5000, corpus_chunk_size: int=100000, max_pairs: int=5... |
def call_api(input_json: Dict[(str, Any)]) -> Dict[(str, Any)]:
url = '
headers = {'Content-Type': 'application/json'}
response = requests.get(url, headers=headers, params=input_json)
if (response.status_code == 200):
return response.json()
else:
return {'status_code': response.statu... |
class XupPl(BaseDecrypter):
__name__ = 'XupPl'
__type__ = 'decrypter'
__version__ = '0.16'
__status__ = 'testing'
__pattern__ = '
__config__ = [('enabled', 'bool', 'Activated', True), ('use_premium', 'bool', 'Use premium account if available', True), ('folder_per_package', 'Default;Yes;No', 'Cre... |
def to_np(item, use_copy=False, dtype=None):
use_copy = (use_copy or np.isscalar(item) or (not equal(get_dtype(item), dtype)))
if isinstance(item, (str, bytes)):
return np.array([item], dtype=object)
elif is_seq_of(item, Number):
return np.array(item, dtype=(get_dtype(item[0]) if (dtype is N... |
.filterwarnings('default::pytest.PytestUnhandledThreadExceptionWarning')
def test_unhandled_thread_exception(pytester: Pytester) -> None:
pytester.makepyfile(test_it='\n import threading\n\n def test_it():\n def oops():\n raise ValueError("Oops")\n\n t = threading.... |
def run_step(context):
logger.debug('started')
context.assert_key_has_value(key='fetchJson', caller=__name__)
fetch_json_input = context.get_formatted('fetchJson')
if isinstance(fetch_json_input, str):
file_path = fetch_json_input
destination_key = None
encoding = config.default_... |
_module()
class NASFCOS_FPN(nn.Module):
def __init__(self, in_channels, out_channels, num_outs, start_level=1, end_level=(- 1), add_extra_convs=False, conv_cfg=None, norm_cfg=None):
super(NASFCOS_FPN, self).__init__()
assert isinstance(in_channels, list)
self.in_channels = in_channels
... |
('a hyperlink having address {address} and fragment {fragment}')
def given_a_hyperlink_having_address_and_fragment(context: Context, address: str, fragment: str):
paragraph_idxs: Dict[(Tuple[(str, str)], int)] = {("''", 'linkedBookmark'): 1, (' "''"): 2, (' "''"): 3, (' 'intro'): 4, (' "''"): 5, ('court-exif.jpg', ... |
def get_seresnext(blocks, cardinality, bottleneck_width, model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs):
if (blocks == 50):
layers = [3, 4, 6, 3]
elif (blocks == 101):
layers = [3, 4, 23, 3]
else:
raise ValueError('Unsupported SE-ResNeXt with... |
_export('keras.experimental.WarmupPiecewise')
class WarmupPiecewise(LearningRateSchedule):
def __init__(self, boundaries, values, warmup_steps, warmup_factor, gradual=True, name=None):
super(WarmupPiecewise, self).__init__()
if (len(boundaries) != (len(values) - 1)):
raise ValueError('Th... |
def test_battery_background(fake_qtile, fake_window, monkeypatch):
ok = BatteryStatus(state=BatteryState.DISCHARGING, percent=0.5, power=15.0, time=1729)
low = BatteryStatus(state=BatteryState.DISCHARGING, percent=0.1, power=15.0, time=1729)
low_background = 'ff0000'
background = '000000'
with monke... |
class MSELoss(torch.nn.Module):
def __init__(self):
super(MSELoss, self).__init__()
def forward(self, preds, heatmap_gt, weight):
losses = ((0.5 * weight) * ((preds - heatmap_gt) ** 2).mean(dim=3).mean(dim=2))
back_loss = losses.mean(dim=1).mean(dim=0)
return back_loss |
class DebertaV2Converter(SpmConverter):
def pre_tokenizer(self, replacement, add_prefix_space):
list_pretokenizers = []
if self.original_tokenizer.split_by_punct:
list_pretokenizers.append(pre_tokenizers.Punctuation(behavior='isolated'))
list_pretokenizers.append(pre_tokenizers.M... |
def combine_to_panoptic_multi_core(img_id2img, inst_by_image, sem_by_image, segmentations_folder, overlap_thr, stuff_area_limit, categories):
cpu_num = multiprocessing.cpu_count()
img_ids_split = np.array_split(list(img_id2img), cpu_num)
print('Number of cores: {}, images per core: {}'.format(cpu_num, len(i... |
def get_dec_inp_targ_seqs(sequence, max_len, start_id, stop_id):
inp = ([start_id] + sequence[:])
target = sequence[:]
if (len(inp) > max_len):
inp = inp[:max_len]
target = target[:max_len]
else:
target.append(stop_id)
assert (len(inp) == len(target))
return (inp, target) |
def read_files(div):
doc_file = (('../raw_files/proc_output/' + 'doc_') + div)
keys_file = (('../raw_files/proc_output/' + 'keys_') + div)
doc_dict = OrderedDict()
keys_dict = OrderedDict()
with open(doc_file) as f_doc:
for line in f_doc:
line_json = json.loads(line)
... |
class GroupParameterItem(ParameterItem):
def __init__(self, param, depth):
ParameterItem.__init__(self, param, depth)
self._initialFontPointSize = self.font(0).pointSize()
self.updateDepth(depth)
self.addItem = None
if ('addText' in param.opts):
addText = param.op... |
def dense(name, x, units, dropout_rate=None, relu=True, layer_norm=False):
with tfv1.variable_scope(name):
bias = variable_on_cpu('bias', [units], tfv1.zeros_initializer())
weights = variable_on_cpu('weights', [x.shape[(- 1)], units], tfv1.keras.initializers.VarianceScaling(scale=1.0, mode='fan_avg'... |
_bp.route('/images/<image_id>/ancestry', methods=['GET'])
_auth
_namespace_repo_from_session
_namespace_enabled
_completion
_cache_headers
_protect
def get_image_ancestry(namespace, repository, image_id, headers):
logger.debug('Checking repo permissions')
permission = ReadRepositoryPermission(namespace, reposit... |
class OmniDeltaLMDecoderLayer(DeltaLMDecoderLayer):
def forward(self, x, encoder_out: Optional[torch.Tensor]=None, encoder_padding_mask: Optional[torch.Tensor]=None, self_attn_mask: Optional[torch.Tensor]=None, self_attn_padding_mask: Optional[torch.Tensor]=None, need_attn: bool=False, need_head_weights: bool=False... |
def main():
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
import struct
args = get_args()
f = open(args.key, 'rb')
key = RSA.importKey(f.read())
f.close()
f = open(args.inf, 'rb')
img = f.read()
f.close()
signer = ... |
def train_triple(model, train_queue, test_queue, optimizer, args, show=True):
losses = []
start = time()
model.train()
for train_epoch in range(args.train_epochs):
temp = []
for (ps_train, qs_train, rs_train, labels_train) in train_queue:
(inferences, regs) = model(ps_train.c... |
def generate_ann(root_path, split, image_infos, preserve_vertical, format):
dst_image_root = osp.join(root_path, 'crops', split)
ignore_image_root = osp.join(root_path, 'ignores', split)
if (split == 'training'):
dst_label_file = osp.join(root_path, f'train_label.{format}')
elif (split == 'val')... |
def test_unveiled_blocks(skip_qtbot):
cosmetic_patches = AM2RCosmeticPatches(unveiled_blocks=True)
dialog = AM2RCosmeticPatchesDialog(None, cosmetic_patches)
skip_qtbot.addWidget(dialog)
skip_qtbot.mouseClick(dialog.unveiled_blocks_check, QtCore.Qt.MouseButton.LeftButton)
assert (dialog.cosmetic_pat... |
def test_shape():
shape = Shape(name='shape', color='blue', material='DIRT')
assert (shape.name == 'shape')
assert (shape.__str__() == 'Shape shape color:blue material:DIRT')
assert (shape.__repr__() == 'Shape')
assert (shape.color == 'blue')
assert (shape.material == 'DIRT')
shape.name = 's... |
def _check_relfile(relname, rootdir, kind):
if os.path.isabs(relname):
raise ValuError(f'{relname!r} is absolute, expected relative')
actual = os.path.join(rootdir, relname)
if (kind == 'dir'):
if (not os.path.isdir(actual)):
raise ValueError(f'directory {actual!r} does not exist... |
def create_user_noverify(username, email, email_required=True, prompts=tuple(), is_possible_abuser=False):
if email_required:
if (not validate_email(email)):
raise InvalidEmailAddressException(('Invalid email address: %s' % email))
else:
email = (email or str(uuid.uuid4()))
(user... |
_funcify.register(Eigh)
def numba_funcify_Eigh(op, node, **kwargs):
uplo = op.UPLO
if (uplo != 'L'):
warnings.warn('Numba will use object mode to allow the `UPLO` argument to `numpy.linalg.eigh`.', UserWarning)
out_dtypes = tuple((o.type.numpy_dtype for o in node.outputs))
ret_sig = numb... |
class LearnerConfig(object):
def __init__(self, episodic, train_learner, eval_learner, pretrained_checkpoint, checkpoint_for_eval, embedding_network, learning_rate, decay_learning_rate, decay_every, decay_rate, experiment_name, pretrained_source):
if (checkpoint_for_eval and pretrained_checkpoint):
... |
class TagsFromPath(Gtk.VBox):
title = _('Tags From Path')
FILTERS = [UnderscoresToSpaces, TitleCase, SplitTag]
handler = TagsFromPathPluginHandler()
def init_plugins(cls):
PluginManager.instance.register_handler(cls.handler)
def __init__(self, parent, library):
super().__init__(spaci... |
def if_api_available(method: Callable) -> Callable:
def decorated(self, *args, **kwargs):
if (not self.rest_api.available):
msg = 'Service unavailable. Try again later.'
return api_error(msg, HTTPStatus.SERVICE_UNAVAILABLE)
return method(self, *args, **kwargs)
return deco... |
class _LocalUnboundNameFinder(_UnboundNameFinder):
def __init__(self, pyobject, parent):
super().__init__(pyobject)
self.parent = parent
def _get_root(self):
return self.parent._get_root()
def is_bound(self, primary, propagated=False):
name = primary.split('.')[0]
if ... |
_module()
class DiceLoss(nn.Module):
def __init__(self, eps=1e-06):
super().__init__()
assert isinstance(eps, float)
self.eps = eps
def forward(self, pred, target, mask=None):
pred = pred.contiguous().view(pred.size()[0], (- 1))
target = target.contiguous().view(target.si... |
def pytest_configure(config: Config) -> None:
xmlpath = config.option.xmlpath
if (xmlpath and (not hasattr(config, 'workerinput'))):
junit_family = config.getini('junit_family')
config.stash[xml_key] = LogXML(xmlpath, config.option.junitprefix, config.getini('junit_suite_name'), config.getini('j... |
.parametrize(['sparse', 'dtype'], [pytest.param(True, 'csr', id='sparse'), pytest.param(False, 'csr', id='sparse2dense'), pytest.param(False, 'dense', id='dense')])
def test_eigen_known_oper(sparse, dtype):
N = qutip.num(10, dtype=dtype)
(spvals, spvecs) = N.eigenstates(sparse=sparse)
expected = np.arange(1... |
class Effect3513(BaseEffect):
runTime = 'early'
type = 'passive'
def handler(fit, implant, context, projectionRange, **kwargs):
fit.appliedImplants.filteredItemMultiply((lambda mod: (mod.item.group.name == 'Cyberimplant')), 'rangeSkillBonus', implant.getModifiedItemAttr('implantSetMordus'), **kwargs... |
def run_step(context):
logger.debug('started')
context.assert_key_has_value('fileWriteJson', __name__)
input_context = context.get_formatted('fileWriteJson')
assert_key_has_value(obj=input_context, key='path', caller=__name__, parent='fileWriteJson')
out_path = Path(input_context['path'])
payloa... |
class PatientIcomData():
def __init__(self, output_dir):
self._data = {}
self._usage_start = {}
self._current_patient_data = {}
self._output_dir = pathlib.Path(output_dir)
def update_data(self, ip, data):
try:
if (self._data[ip][(- 1)][26] == data[26]):
... |
def decompose_bivector(F):
c1 = F
F2 = (F * F)
if (F2 == 0):
return ((+ F), (0 * e1))
c2 = (0.5 * F2(4))
c1_2 = (c1 * c1)[()]
c2_2 = (c2 * c2)[()]
lambs = np.roots([1, (- c1_2), c2_2])
F1 = (((c1 * c2) - (lambs[0] * c1)) / (lambs[1] - lambs[0]))
F2 = (((c1 * c2) - (lambs[1] *... |
def dice_coefficient(pred, gt, smooth=1e-05):
N = gt.shape[0]
pred[(pred >= 1)] = 1
gt[(gt >= 1)] = 1
pred_flat = pred.reshape(N, (- 1))
gt_flat = gt.reshape(N, (- 1))
intersection = (pred_flat * gt_flat).sum(1)
unionset = (pred_flat.sum(1) + gt_flat.sum(1))
dice = (((2 * intersection) +... |
class TestTrainerDistributedNeuronCore(TestCasePlus):
_torch_neuroncore
def test_trainer(self):
distributed_args = f'''
-m torch.distributed.launch
--nproc_per_node=2
--master_port={get_torch_dist_unique_port()}
{self.test_file_dir}/test_trainer_distribute... |
def test_compress():
obj1 = QobjEvo([[qeye(N), 't'], [qeye(N), 't'], [qeye(N), 't']])
assert (obj1.num_elements == 1)
obj2 = QobjEvo([[qeye(N), 't'], [qeye(N), 't'], [qeye(N), 't']], compress=False)
assert (obj2.num_elements == 3)
_assert_qobjevo_equivalent(obj1, obj2)
obj3 = obj2.copy()
ass... |
class ShmemVecEnv(VecEnv):
def __init__(self, env_fns, spaces=None):
if spaces:
(observation_space, action_space) = spaces
else:
logger.log('Creating dummy env object to get spaces')
with logger.scoped_configure(format_strs=[]):
dummy = env_fns[0](... |
.parametrize('kwargs, is_valid', [({'choices_provider': fake_func}, True), ({'completer': fake_func}, True), ({'choices_provider': fake_func, 'completer': fake_func}, False)])
def test_apcustom_choices_callable_count(kwargs, is_valid):
parser = Cmd2ArgumentParser()
try:
parser.add_argument('name', **kwa... |
def test_freqresp_warn_infinite():
sys_finite = ctrl.tf([1], [1, 0.01])
sys_infinite = ctrl.tf([1], [1, 0.01, 0])
np.testing.assert_almost_equal(sys_finite(0), 100)
np.testing.assert_almost_equal(sys_finite(0, warn_infinite=False), 100)
np.testing.assert_almost_equal(sys_finite(0, warn_infinite=True... |
class WeightedDiceLoss(nn.Module):
def __init__(self, axis=((- 1), (- 2), (- 3)), smooth=1e-06):
super().__init__()
self.axis = axis
self.smooth = smooth
def forward(self, y_pred, y_truth):
return (1 - torch.mean((((2 * torch.sum((y_pred * y_truth), dim=self.axis)) + self.smooth)... |
class DatagramProtocolClient(asyncio.Protocol):
def __init__(self, server, port, logger, client, retries=3, timeout=30):
self.transport = None
self.port = port
self.server = server
self.logger = logger
self.retries = retries
self.timeout = timeout
self.client ... |
('a Settings object {with_or_without} odd and even page headers as settings')
def given_a_Settings_object_with_or_without_odd_and_even_hdrs(context, with_or_without):
testfile_name = {'with': 'doc-odd-even-hdrs', 'without': 'sct-section-props'}[with_or_without]
context.settings = Document(test_docx(testfile_nam... |
def get_network(config):
if (config.data.image_size < 96):
return functools.partial(NCSNv2, config=config)
elif (96 <= config.data.image_size <= 128):
return functools.partial(NCSNv2_128, config=config)
elif (128 < config.data.image_size <= 256):
return functools.partial(NCSNv2_256, ... |
class OnnxConfig(ABC):
default_fixed_batch = 2
default_fixed_sequence = 8
default_fixed_num_choices = 4
torch_onnx_minimum_version = version.parse('1.8')
_tasks_to_common_outputs = {'causal-lm': OrderedDict({'logits': {0: 'batch', 1: 'sequence'}}), 'default': OrderedDict({'last_hidden_state': {0: 'b... |
def loadIcons():
iconDir = os.path.join(pyzo.pyzoDir, 'resources', 'icons')
dummyIcon = IconArtist().finish()
pyzo.icons = ssdf.new()
for fname in os.listdir(iconDir):
if fname.endswith('.png'):
try:
name = fname.split('.')[0]
name = name.replace('pyzo... |
def test_populate_services_addresses(service_registry_address, private_keys, web3, contract_manager):
(c1_service_proxy, _) = deploy_service_registry_and_set_urls(private_keys=private_keys, web3=web3, contract_manager=contract_manager, service_registry_address=service_registry_address)
addresses = [privatekey_t... |
def convert_interactive(op):
import tempfile
import os
import subprocess
import queue
[fh, out_fn] = tempfile.mkstemp(suffix='.mrc')
os.close(fh)
cmd = [str(op['situs_pdb2vol_program']), op['pdb_file'], out_fn]
print(cmd)
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=sub... |
class Wav2VecFeatureReader(object):
def __init__(self, cp_file, layer):
state = fairseq.checkpoint_utils.load_checkpoint_to_cpu(cp_file)
self.layer = layer
if ('cfg' in state):
w2v_args = state['cfg']
task = fairseq.tasks.setup_task(w2v_args.task)
model = ... |
class BaseModel(pybamm.BaseSubModel):
def __init__(self, param, domain, options, phase='primary'):
super().__init__(param, domain, options=options, phase=phase)
def _get_standard_active_material_variables(self, eps_solid):
param = self.param
phase_name = self.phase_name
(domain, ... |
class TestPythonLayer(unittest.TestCase):
def setUp(self):
net_file = python_net_file()
self.net = caffe.Net(net_file, caffe.TRAIN)
os.remove(net_file)
def test_forward(self):
x = 8
self.net.blobs['data'].data[...] = x
self.net.forward()
for y in self.net.... |
(cc=STDCALL, params={'hHandle': HANDLE, 'dwMilliseconds': DWORD})
def hook_WaitForSingleObject(ql: Qiling, address: int, params):
hHandle = params['hHandle']
handle = ql.os.handle_manager.get(hHandle)
if handle:
target_thread = handle.obj
ql.os.thread_manager.cur_thread.waitfor(target_thread... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.