code stringlengths 281 23.7M |
|---|
class ConvNormal(nn.Module):
def __init__(self, nIn, nOut, bottleneck, bnWidth):
super(ConvNormal, self).__init__()
self.conv_normal = ConvBN(nIn, nOut, 'normal', bottleneck, bnWidth)
def forward(self, x):
if (not isinstance(x, list)):
x = [x]
res = [x[0], self.conv_n... |
def test_cswap_unitary():
cswap = CSwap(bitsize=4)
np.testing.assert_array_equal(np.eye((2 ** (4 * 2))), _set_ctrl_swap(0, cswap).tensor_contract())
qubits = cirq.LineQubit.range(8)
(q_x, q_y) = (qubits[:4], qubits[4:])
unitary = cirq.unitary(cirq.Circuit((cirq.SWAP(x, y) for (x, y) in zip(q_x, q_y)... |
class Converter():
def __init__(self, path: str, dest: str, language: str='en', show_err: bool=False):
self.path = path
self.dest = dest
self.language = language
self.show_err = show_err
def delete_directory(self, path: Path):
if (not path.exists()):
return
... |
def policy_nn(state, state_dim, action_dim, initializer):
w1 = tf.get_variable('W1', [state_dim, 512], initializer=initializer, regularizer=tf.contrib.layers.l2_regularizer(0.01))
b1 = tf.get_variable('b1', [512], initializer=tf.constant_initializer(0.0))
h1 = tf.nn.relu((tf.matmul(state, w1) + b1))
w2 ... |
.parametrize('parser', [('scenario-outline',)], indirect=['parser'])
def test_parse_feature_with_scenario_outline(parser):
feature = parser.parse()
assert (len(feature.scenarios) == 1)
assert isinstance(feature.scenarios[0], ScenarioOutline)
assert (len(feature.scenarios[0].scenarios) == 2)
assert (... |
def get_backbone(p):
if (p['model_kwargs']['pretraining'] == 'imagenet_supervised'):
print('Loaded model with ImageNet supervised initialization.')
return resnet50(pretrained=True)
elif (p['model_kwargs']['pretraining'] == 'random'):
print('Loaded model with random initialization.')
... |
class KSMCollector(diamond.collector.Collector):
def get_default_config_help(self):
config_help = super(KSMCollector, self).get_default_config_help()
config_help.update({'ksm_path': 'location where KSM kernel data can be found'})
return config_help
def get_default_config(self):
c... |
def _retrieve_checkpoint_dirpaths(dirpath: str) -> List[str]:
def sort_fn(path: str) -> Tuple[(int, int)]:
x = os.path.basename(path)
return (int(x.split('_')[1]), int(x.split('_')[3]))
fs = get_filesystem(dirpath)
contents = fs.ls(dirpath, detail=True)
contents = [item['name'] for item ... |
def run(args: Union[(str, List[str])], *, log_run_to_stderr: bool=True, abbreviate_non_option_arguments: bool=False, check: bool=True, text: bool=True, **subprocess_run_kwargs) -> subprocess.CompletedProcess:
subprocess_run_kwargs.update(check=check, text=text)
if log_run_to_stderr:
cmd_desc: Tuple[(str... |
class VariableDeviceChooser(object):
def __init__(self, num_tasks=0, job_name='ps', device_type='CPU', device_index=0, replica=None):
self._job_name = job_name
self._device_type = device_type
self._device_index = device_index
self._replica = replica
self._num_tasks = num_task... |
.parametrize('metadata_version', [None, '0.1', '0.2'])
def test_uninstall_with_missing_interpreter(pipx_temp_env, metadata_version):
executable_path = (constants.LOCAL_BIN_DIR / app_name('pycowsay'))
assert (not run_pipx_cli(['install', 'pycowsay']))
assert executable_path.exists()
mock_legacy_venv('pyc... |
class TestMetadataConstructionAndProperties(unittest.TestCase):
def assertEqualColumns(self, obs_columns, exp):
obs = [(name, props.type) for (name, props) in obs_columns.items()]
self.assertEqual(obs, exp)
def test_minimal(self):
md = Metadata(pd.DataFrame({}, index=pd.Index(['a'], name... |
def evaluate_batch_retrieval(args, rag_model, questions):
def strip_title(title):
if title.startswith('"'):
title = title[1:]
if title.endswith('"'):
title = title[:(- 1)]
return title
retriever_input_ids = rag_model.retriever.question_encoder_tokenizer.batch_enco... |
class Keithley2260B(Instrument):
def __init__(self, adapter, name='Keithley 2260B DC Power Supply', read_termination='\n', **kwargs):
super().__init__(adapter, name, read_termination=read_termination, **kwargs)
output_enabled = Instrument.control('OUTPut?', 'OUTPut %d', 'A boolean property that controls... |
_unraisablehook()
def test_async_function_implemented_in_C() -> None:
async def agen_fn(record: list[str]) -> AsyncIterator[None]:
assert (not _core.currently_ki_protected())
record.append('the generator ran')
(yield)
run_record: list[str] = []
agen = agen_fn(run_record)
_core.ru... |
class WebAppData(TelegramObject):
__slots__ = ('data', 'button_text')
def __init__(self, data: str, button_text: str, *, api_kwargs: Optional[JSONDict]=None):
super().__init__(api_kwargs=api_kwargs)
self.data: str = data
self.button_text: str = button_text
self._id_attrs = (self.... |
def _build_proj_equation(free_dims, bound_dims, output_dims):
input_str = ''
kernel_str = ''
output_str = ''
bias_axes = ''
letter_offset = 0
for i in range(free_dims):
char = _CHR_IDX[(i + letter_offset)]
input_str += char
output_str += char
letter_offset += free_dim... |
def process_one(data):
utterances = data[0]
reps = data[1]
summary = data[2]
weight_matrix = []
for i in range((len(reps) - 1), 0, (- 1)):
q_rep = reps[i]
k_rep = reps[:i]
weights = cosine_sim(q_rep, k_rep)
weight_matrix.append(weights)
return (utterances, weight_... |
class TestSQLiteTLE(unittest.TestCase):
def setUp(self):
from pyorbital.tlefile import SQLiteTLE
from pyorbital.tlefile import Tle
from tempfile import TemporaryDirectory
self.temp_dir = TemporaryDirectory()
self.db_fname = os.path.join(self.temp_dir.name, 'tle.db')
s... |
class UnZip(BaseExtractor):
__name__ = 'UnZip'
__type__ = 'extractor'
__version__ = '1.28'
__status__ = 'stable'
__description__ = 'ZIP extractor plugin'
__license__ = 'GPLv3'
__authors__ = [('Walter Purcaro', '')]
VERSION = '{}.{}.{}'.format(sys.version_info[0], sys.version_info[1], sys... |
class AutoapiClassDocumenter(AutoapiDocumenter, autodoc.ClassDocumenter, _AutoapiDocstringSignatureMixin):
objtype = 'apiclass'
directivetype = 'class'
doc_as_attr = False
priority = ((autodoc.ClassDocumenter.priority * 100) + 100)
def can_document_member(cls, member, membername, isattr, parent):
... |
class SegmentationDataGenerator():
def __init__(self, input_shape=(128, 128), batch_size=32, preprocess=None, augs=None):
self.input_shape = input_shape
self.batch_size = batch_size
self.preprocess = preprocess
self.augs = augs
def _read_image_train(self, id):
if os.path.... |
def chunks(iterator: Iterator[T], n: int) -> Iterator[Iterator[T]]:
empty_iterator = True
for first in iterator:
empty_iterator = False
rest_of_chunk = itertools.islice(iterator, 0, (n - 1))
(yield itertools.chain([first], rest_of_chunk))
if empty_iterator:
(yield iter([])) |
def process_account(account, i):
values = account.split('')
cookie = values[0]
print(f'''
======={i}=======''')
current_time = str(int(time.time()))
sign_str = f'key=4fck9x4dqa6linkman3ho9b1quarto49x0yp706qi5185o&time={current_time}'
sha256_hash = hashlib.sha256(sign_str.encode())
sign = sha... |
def cross_layer_equalization_auto_stepwise():
model = tf.keras.applications.resnet50.ResNet50(weights=None, classes=10)
(model_for_cle, _) = replace_relu6_with_relu(model)
(folded_pairs, model) = fold_all_batch_norms(model_for_cle)
bn_dict = {}
for (conv_or_linear, bn) in folded_pairs:
bn_di... |
class bertLSTMCRF(object):
def __init__(self, params, bert_config):
self.dropout_rate = params['dropout_prob']
self.num_labels = params['num_labels']
self.rnn_size = params['rnn_size']
self.num_layers = params['num_layers']
self.hidden_units = params['hidden_units']
s... |
class FcBlockWOutput(nn.Module):
def __init__(self, fc_params, output_params, flatten=False):
super(FcBlockWOutput, self).__init__()
input_size = fc_params[0]
output_size = fc_params[1]
add_output = output_params[0]
num_classes = output_params[1]
self.output_id = outp... |
def parallel_data_prefetch(func: callable, data, n_proc, target_data_type='ndarray', cpu_intensive=True, use_worker_id=False):
if (isinstance(data, np.ndarray) and (target_data_type == 'list')):
raise ValueError('list expected but function got ndarray.')
elif isinstance(data, abc.Iterable):
if i... |
class GELS(Function):
def forward(ctx, A, b):
u = torch.cholesky(torch.matmul(A.transpose((- 1), (- 2)), A), upper=True)
ret = torch.cholesky_solve(torch.matmul(A.transpose((- 1), (- 2)), b), u, upper=True)
ctx.save_for_backward(u, ret, A, b)
return ret
def backward(ctx, grad_out... |
class ImportExportTagsAndTrackUserDataPlugin(SongsMenuPlugin):
PLUGIN_ID = _PLUGIN_ID
PLUGIN_NAME = _('Import / Export')
PLUGIN_DESC = _('Imports and exports tags and track user data.')
PLUGIN_ICON = Icons.EDIT_COPY
plugin_handles = each_song(is_finite)
_album_id_to_export_path: MutableMapping[(... |
def annotate(*, decision=None, output=None, varHeuristic=None, valHeuristic=None, filtering=None, prepro=None, search=None, restarts=None):
def add_annotation(obj, Ann):
if obj:
ann = Ann(obj)
assert (type(ann) not in AnnEntities.items_types), 'This type of annotation can be specifie... |
class CosineAnnealingRestartLR(_LRScheduler):
def __init__(self, optimizer, periods, restart_weights=(1,), eta_min=0, last_epoch=(- 1)):
self.periods = periods
self.restart_weights = restart_weights
self.eta_min = eta_min
assert (len(self.periods) == len(self.restart_weights)), 'peri... |
class WTFPython(commands.Cog):
def __init__(self, bot: Bot):
self.bot = bot
self.headers: dict[(str, str)] = {}
self.fetch_readme.start()
(minutes=60)
async def fetch_readme(self) -> None:
async with self.bot. as resp:
log.trace('Fetching the latest WTF Python REA... |
class CrossEntropyLoss(BaseLoss):
def __init__(self, label_name):
self._label_name = label_name
def loss_fn(self, logits, examples):
labels = tf.to_float(examples[self._label_name])
return self._cross_entropy_loss(logits, labels)
def _cross_entropy_loss(self, logits, labels):
... |
def add_image_net_computational_nodes_in_graph(session: tf.Session, logits_name: str, num_classes: int):
with session.graph.as_default():
y_hat = session.graph.get_tensor_by_name(logits_name)
y_hat_argmax = tf.argmax(y_hat, axis=1)
y = tf.placeholder(tf.int64, shape=[None, num_classes], name... |
def main(argv: List[str]) -> None:
args = parse_args(argv)
input_dir = args.input_dir
output_dir = args.output_dir
input_files = [os.path.join(input_dir, f'day_{i}_sparse.npy') for i in range(DAYS)]
if (not input_files):
raise ValueError(f"There are no files that end with '_sparse.npy' in th... |
def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments))
if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')):
(model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
(model_args, data_arg... |
class SelectPresetWidget(QtWidgets.QWidget, Ui_SelectPresetWidget):
CanGenerate = QtCore.Signal(bool)
for_multiworld: bool = False
_logic_settings_window: (CustomizePresetDialog | None) = None
_preset_history: (PresetHistoryDialog | None) = None
_has_set_from_last_selected: bool = False
_preset_... |
class SMU():
def __init__(self, parent, channel, smu_type, name, **kwargs):
self._b1500 = weakref.proxy(parent)
channel = strict_discrete_set(channel, range(1, 11))
self.channel = channel
smu_type = strict_discrete_set(smu_type, ['HRSMU', 'MPSMU', 'HPSMU', 'MCSMU', 'HCSMU', 'DHCSMU',... |
def test_override():
class TestObject():
def __init__(self):
self.v = None
o = TestObject()
o.v = 'a'
with qcore.override(o, 'v', 'b'):
assert_eq(o.v, 'b')
try:
with qcore.override(o, 'v', 'c'):
assert_eq(o.v, 'c')
raise Not... |
class PReNetTS(BaseDeepAD):
def __init__(self, epochs=100, batch_size=64, lr=0.001, network='Transformer', seq_len=30, stride=1, rep_dim=128, hidden_dims='512', act='GELU', bias=False, n_heads=8, d_model=512, attn='self_attn', pos_encoding='fixed', norm='BatchNorm', epoch_steps=(- 1), prt_steps=10, device='cuda', v... |
def get_config(name):
config = {}
if (name.upper() == 'ARID'):
config['num_classes'] = 11
else:
logging.error("Configs for dataset '{}'' not found".format(name))
raise NotImplemented
logging.debug("Target dataset: '{}', configs: {}".format(name.upper(), config))
return config |
class Conv2dSubSampler(LayerSubSampler):
def verify_layers(self, orig_layer: torch.nn.Module, pruned_layer: torch.nn.Module):
assert isinstance(orig_layer, torch.nn.Conv2d)
assert isinstance(pruned_layer, torch.nn.Conv2d)
assert (orig_layer.dilation == (1, 1)), 'No Conv2d layers supported fo... |
class Commit():
def __init__(self, commit_hash, category, topic, title):
self.commit_hash = commit_hash
self.category = category
self.topic = topic
self.title = title
def __eq__(self, other):
if (not isinstance(other, self.__class__)):
return False
ret... |
def get_internal_env_config() -> dict[(str, Any)]:
from hatch.env.internal import build, static_analysis
internal_config = {}
for (env_name, env_config) in (('hatch-build', build.get_default_config()), ('hatch-static-analysis', static_analysis.get_default_config())):
env_config['template'] = env_nam... |
def unique_type_in(l, tpe=None):
if isinstance(l, (list, tuple, set, frozenset)):
if (len(l) == 0):
return None
for v in l:
t = unique_type_in(v, tpe)
if (t is False):
return False
if (tpe is None):
tpe = t
retur... |
class TestDataDownload():
(autouse=True)
def _setup_custom_configs(self, tmpdir):
_setup_custom_composite_config(tmpdir)
_setup_custom_reader_config(tmpdir)
_setup_custom_writer_config(tmpdir)
self.tmpdir = tmpdir
.parametrize('comp_sensors', [tuple(), None, ('visir',)])
... |
class Effect4458(BaseEffect):
runTime = 'early'
type = 'passive'
def handler(fit, implant, context, projectionRange, **kwargs):
fit.appliedImplants.filteredItemMultiply((lambda target: target.item.requiresSkill('Cybernetics')), 'scanLadarStrengthPercent', implant.getModifiedItemAttr('implantSetRepub... |
def test_compose():
with pytest.raises(TypeError):
Compose('LoadImageFromFile')
target_keys = ['img', 'img_rename', 'img_metas']
img = np.random.randn(256, 256, 3)
results = dict(img=img, img_file='test_image.png')
test_pipeline = [dict(type='Collect', keys=['img', ('img', 'img_rename')], me... |
class LinOpWithoutGetParamNames(LinearOperator):
def __init__(self, mat, is_hermitian=False):
super(LinOpWithoutGetParamNames, self).__init__(shape=mat.shape, is_hermitian=is_hermitian, dtype=mat.dtype, device=mat.device)
self.mat = mat
self.implemented_methods = []
def _mv(self, x):
... |
def crop_image(img):
(w, h) = img.size
if (h == w):
return img
normal = min(h, w)
diff_w = (w - normal)
diff_h = (h - normal)
crop_top = (diff_h // 2)
crop_bot = ((diff_h // 2) + (diff_h % 2))
crop_left = (diff_w // 2)
crop_right = ((diff_w // 2) + (diff_w % 2))
box = (cr... |
def inference_small_config(x, c, trl_type, rank):
c['bottleneck'] = False
c['ksize'] = 3
c['stride'] = 1
with tf.variable_scope('scale1'):
c['conv_filters_out'] = 16
c['block_filters_internal'] = 16
c['stack_stride'] = 1
x = conv(x, c)
x = bn(x, c)
x = act... |
_module()
class CocoCaptionOVDDataset(CocoDataset):
def prepare_data(self, idx):
data_info = self.get_data_info(idx)
if data_info['has_caption']:
return self.pipeline(data_info)
else:
return None
def parse_data_info(self, raw_data_info: dict):
img_info = r... |
def read_tables(config, c=None):
table_reader = build_reader(data_format=config['file_format'], basepath=config['data_dir'], split_row_groups=config['split_row_groups'], backend=config['backend'])
date_dim_cols = ['d_date_sk', 'd_date']
web_page_cols = ['wp_web_page_sk', 'wp_type']
web_sales_cols = ['ws... |
class ScriptError(Exception):
def __init__(self, errorinfo):
self._errorinfo = dict(errorinfo)
def __repr__(self):
return 'ScriptError({})'.format(self._errorinfo)
def message(self):
msg = self._errorinfo.get(NSAppleScriptErrorMessage)
if (not msg):
msg = self._er... |
class TestMonochromeColor(unittest.TestCase):
def test_main_functionality(self):
self.assertEqual(monochrome_color((255, 255, 255)), COLORS['white'])
self.assertEqual(monochrome_color((254, 254, 254)), COLORS['white'])
self.assertEqual(monochrome_color((255, 112, 112)), COLORS['white'])
... |
def compute_weights(labels, classes, count, verbose=False):
if verbose:
print('')
sum_weights = 0
for c in range(len(classes)):
if ((classes[c] / count) > 0):
sum_weights += (count / classes[c])
sum_weight_norm = 0
weights = list()
for c in range(len(classes)):
... |
def main(args):
tf.logging.set_verbosity(tf.logging.INFO)
model_cls = models.get_model(args.model)
params = default_parameters()
params = merge_parameters(params, model_cls.get_parameters())
params = import_params(args.checkpoint, args.model, params)
override_parameters(params, args)
with tf... |
class SettingsDialog(QtWidgets.QDialog):
def __init__(self, parent):
super().__init__(parent)
self.setWindowTitle(f'{constants.APPNAME} Settings')
tabs = QtWidgets.QTabWidget()
misc = QtWidgets.QWidget()
misc_layout = QtWidgets.QGridLayout()
misc.setLayout(misc_layout... |
def _compute_dloss_by_dmin_dmax_and_dx(inputs: tf.Tensor, encoding_min: tf.Variable, encoding_max: tf.Variable, op_mode: tf.Variable, bitwidth: tf.Variable, is_symmetric: tf.Variable, grad: tf.Tensor) -> Tuple:
x = tf.cast(inputs, tf.float32)
bitwidth = tf.cast(bitwidth, tf.float32)
op_mode = tf.cast(op_mod... |
def SetFlags(os, binType, type, defaultFlags, advanced=True):
configLines = list()
configLines.append(' <Flags>\n')
usingUB = False
for flag in defaultFlags:
if (len(flag) > 0):
configLines.append((' <%s/>\n' % flag))
if (flag == 'PCHEAP_CONFIG_LOADED_WITH_UTILITY_BUR... |
.skipif((not ((platform.system() == 'Windows') and randovania.is_frozen())), reason='only works in frozen Windows')
def test_find_bad_installation():
progress_update = MagicMock()
hash_list: dict[(str, str)] = json_lib.read_path(randovania.get_data_path().joinpath('frozen_file_list.json'))
result = installa... |
class DownsampleBlock(nn.Module):
def __init__(self, in_channels, out_channels, x0_channels, dilations):
super(DownsampleBlock, self).__init__()
inc_channels = (out_channels - in_channels)
self.pool = nn.AvgPool2d(kernel_size=3, stride=2, padding=1)
self.eesp = ESPBlock(in_channels=i... |
def test_shebang_matches():
assert util.shebang_matches('#!/usr/bin/env python\n', 'python(2\\.\\d)?')
assert util.shebang_matches('#!/usr/bin/python2.4', 'python(2\\.\\d)?')
assert util.shebang_matches('#!/usr/bin/startsomethingwith python', 'python(2\\.\\d)?')
assert util.shebang_matches('#!C:\\Python... |
_bool('is_required_a', 'is_required_b')
def test_flat(debug_ctx, debug_trail, trail_select, is_required_a, is_required_b, acc_schema):
dumper_getter = make_dumper_getter(shape=shape(TestField('a', acc_schema.accessor_maker('a', is_required_a)), TestField('b', acc_schema.accessor_maker('b', is_required_b))), name_la... |
class TestOpenAICompatibility():
def test_models(self, openai_testing_model):
models = openai.Model.list()
assert (len(models['data']) == 1), 'Only the test model should be returned'
assert (models.data[0].id == openai_testing_model), 'The test model id should match'
def test_completions... |
class Xmate3RobotiqDefaultConfig():
def __init__(self) -> None:
self.urdf_path = '{ASSET_DIR}/xmate3_robotiq/xmate3_robotiq.urdf'
self.urdf_config = dict(_materials=dict(gripper=dict(static_friction=2.0, dynamic_friction=2.0, restitution=0.0)), link=dict(left_inner_finger_pad=dict(material='gripper'... |
def get_acq_time_exp(start_time, nlines):
tline_exp = np.zeros(464, dtype='datetime64[ms]')
tline_exp[0] = np.datetime64('NaT')
tline_exp[(- 1)] = np.datetime64('NaT')
tline_exp[1:(- 1)] = np.datetime64(start_time)
tline_exp[1:(- 1)] += np.arange((nlines - 2)).astype('timedelta64[ms]')
return tl... |
def calculateSSIM():
original_name = ((str(BASE_TRUTH_DIR) + '/6400/') + str(SLIDE_NAME))
print(original_name)
original = cv2.imread(original_name)
synthesized_name = ((str(BASE_TRUTH_DIR) + '/H/') + str(SLIDE_NAME))
print(synthesized_name)
synthesized = cv2.imread(synthesized_name)
compare_... |
('torchx.runner.events.record')
class LogEventTest(unittest.TestCase):
def assert_torchx_event(self, expected: TorchxEvent, actual: TorchxEvent) -> None:
self.assertEqual(expected.session, actual.session)
self.assertEqual(expected.app_id, actual.app_id)
self.assertEqual(expected.api, actual.... |
class InteractionProjectionArchTest(unittest.TestCase):
def test_basic(self) -> None:
D = 3
B = 10
keys = ['f1', 'f2']
F = len(keys)
F1 = 2
F2 = 2
I1 = DenseArch(in_features=((2 * D) + D), layer_sizes=[(2 * D), (F1 * D)])
I2 = DenseArch(in_features=((2... |
def check_models_are_in_init():
models_not_in_init = []
dir_transformers = dir(transformers)
for module in get_model_modules():
models_not_in_init += [model[0] for model in get_models(module, include_pretrained=True) if (model[0] not in dir_transformers)]
models_not_in_init = [model for model in... |
class ModelEMA(object):
def __init__(self, model, decay=0.9999, updates=0):
self.ema = deepcopy(model).eval()
self.updates = updates
self.decay = (lambda x: (decay * (1 - math.exp(((- x) / 2000.0)))))
for p in self.ema.parameters():
p.requires_grad_(False)
def update(... |
def load_pretrain(model, pretrained_path):
logger.info('load pretrained model from {}'.format(pretrained_path))
device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))
pretrained_dict = torch.load(pretrained_path, map_location=device)
if ('state_dict' in pretrained_dict.keys()):
... |
def build_tqdm(n: int, message: typing.Optional[str]=None) -> typing.Tuple[(typing.Callable, typing.Callable)]:
if (message is None):
message = f'Running for {n:,} iterations'
tqdm_bars = {}
if (n > 20):
print_rate = int((n / 20))
else:
print_rate = 1
remainder = (n % print_r... |
class Effect6786(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Shield Command')), 'warfareBuff4Value', src.getModifiedItemAttr('shipBonusICS3'), skill='Industrial Command Ships', **kwargs)
... |
class AutopartUsage_TestCase(CommandSequenceTest):
def runTest(self):
correct_command_sequences = ['part / --size=2048', 'partition / --size=2048', 'autopart', 'raid / --level=1 --device=md0 raid.01', 'logvol / --vgname=foo --size=2000 --name=bar', 'volgroup foo pv.01']
for sequence in correct_comma... |
def _get_filenames_to_download(channels, granules):
if any((('DNB' in chan) for chan in channels)):
(yield from _yield_specific_granules(GDNBO_URLS, granules))
if any((('I' in chan) for chan in channels)):
(yield from _yield_specific_granules(GITCO_URLS, granules))
if any((('M' in chan) for ... |
def _parse_datetime_header(value: str) -> datetime.datetime:
match = re.match('^(?P<datetime>.*?)(?P<tzoffset>[+-]\\d{4})?$', value)
dt = datetime.datetime.strptime(match.group('datetime'), '%Y-%m-%d %H:%M')
tzoffset = match.group('tzoffset')
if (tzoffset is not None):
(plus_minus_s, rest) = (tz... |
def resp_update_push_rules_project():
with responses.RequestsMock() as rsps:
rsps.add(method=responses.GET, url=' json=push_rules_content, content_type='application/json', status=200)
rsps.add(method=responses.PUT, url=' json=push_rules_content, content_type='application/json', status=201)
(... |
def checkStyle():
print('flake8: check all code against mandatory error set...')
errors = ','.join(FLAKE_MANDATORY)
cmd = (['flake8', ('--select=' + errors)] + FLAKE_CHECK_PATHS)
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
output = proc.stdout.read().decode('utf-8')
ret = proc.wait()
... |
_config
def test_spiral_bottom_anticlockwise(manager):
manager.c.next_layout()
manager.c.next_layout()
manager.c.next_layout()
manager.test_window('one')
assert_dimensions(manager, 0, 0, 798, 598)
manager.test_window('two')
assert_dimensions(manager, 0, 0, 798, 298)
manager.test_window('... |
(frozen=True)
class InputShape(BaseShape, Generic[T]):
fields: VarTuple[InputField]
params: VarTuple[Param]
kwargs: Optional[ParamKwargs]
constructor: Callable[(..., T)]
fields_dict: Mapping[(str, InputField)] = field(init=False, hash=False, repr=False, compare=False)
def allow_kwargs(self) -> b... |
class SentenceBERT():
def __init__(self, model_path: Union[(str, Tuple)]=None, sep: str=' ', **kwargs):
self.sep = sep
if isinstance(model_path, str):
self.q_model = SentenceTransformer(model_path)
self.doc_model = self.q_model
elif isinstance(model_path, tuple):
... |
def _transverse_mercator__to_cf(conversion):
params = _to_dict(conversion)
return {'grid_mapping_name': 'transverse_mercator', 'latitude_of_projection_origin': params['latitude_of_natural_origin'], 'longitude_of_central_meridian': params['longitude_of_natural_origin'], 'false_easting': params['false_easting'], ... |
def load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=False):
if ((args.local_rank not in [(- 1), 0]) and (not evaluate)):
torch.distributed.barrier()
input_file = (args.predict_file if evaluate else args.train_file)
cached_features_file = os.path.join(os.path.dirname(input_fi... |
def test_import_dotted_library(capsys: CaptureFixture, caplog: LogCaptureFixture) -> None:
caplog.set_level(logging.INFO)
original_module = sys.modules.pop('xml.etree.ElementTree')
expected_out = 'INFO (TEST): Welcome to cElementTree!'
expected_err = 'WARNING (TEST): Monkey-patched version of cElementTr... |
def create_dumped_response():
dumped_issues = _load_dumped_issues()
for issue in dumped_issues:
issue.pop('milestone', None)
issue.pop('performed_via_github_app', None)
issue.pop('draft', None)
if (issue['closed_at'] is not None):
issue['closed_at'] = issue['closed_at... |
def with_implementation(fn: object, implementation_fn: Impl) -> Iterator[None]:
if (fn in ArgSpecCache.DEFAULT_ARGSPECS):
with qcore.override(ArgSpecCache.DEFAULT_ARGSPECS[fn], 'impl', implementation_fn):
(yield)
else:
checker = pyanalyze.checker.Checker()
argspec = checker.a... |
_cache(maxsize=5000)
def to_checksum_address(address: AddressTypes) -> ChecksumAddress:
out = ''
v = int.from_bytes(keccak(bytes(address.hex(), 'ascii')), byteorder='big')
for (i, char) in enumerate(address.hex()):
if (char in ''):
out += char
else:
out += (char.upper... |
(frozen=True, order=True)
class AmmoPickupDefinition(JsonDataclass):
game: RandovaniaGame = dataclasses.field(metadata={'init_from_extra': True})
name: str = dataclasses.field(metadata={'init_from_extra': True})
model_name: str
offworld_models: frozendict[(RandovaniaGame, str)]
items: tuple[(str, ..... |
def calculate_mro(info: TypeInfo, obj_type: (Callable[([], Instance)] | None)=None) -> None:
mro = linearize_hierarchy(info, obj_type)
assert mro, f'Could not produce a MRO at all for {info}'
info.mro = mro
info.fallback_to_any = any((baseinfo.fallback_to_any for baseinfo in info.mro))
type_state.re... |
def pytest_collection_modifyitems(items, config):
sanity = config.getoption('--sanity', False)
non_interactive = config.getoption('--non-interactive', False)
remaining = []
deselected = []
for item in items:
if _skip_item(item, sanity, non_interactive):
deselected.append(item)
... |
class GenericTests(SphinxIntegrationTests):
build_path = 'tests/sphinx_generic'
def test_headings(self):
output = self.read_file('index.html')
self.assertIn('<h1>Heading 1<a class="headerlink" href="#heading-1" title="Permalink to this headline"></a></h1>', output)
self.assertIn('<h2>Hea... |
class TPlaylistMenu(TestCase):
SONG = AudioFile({'title': 'two', 'artist': 'mu', '~filename': dummy_path('/dev/zero')})
SONGS = [AudioFile({'title': 'one', 'artist': 'piman', '~filename': dummy_path('/dev/null')}), SONG]
def setUp(self):
self.assertTrue(((_TEMP_DIR in _DEFAULT_PLAYLIST_DIR) or (os.n... |
def multiline_merge(lines, current_event, re_after, re_before):
events = []
for line in lines:
if (re_before and re_before.match(line)):
current_event.append(line)
elif (re_after and current_event and re_after.match(current_event[(- 1)])):
current_event.append(line)
... |
class Sync(Cog):
def __init__(self, bot: Bot) -> None:
self.bot = bot
async def cog_load(self) -> None:
(await self.bot.wait_until_guild_available())
guild = self.bot.get_guild(constants.Guild.id)
if (guild is None):
return
attempts = 0
while True:
... |
class _FlaskLoginClient(FlaskClient):
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
fresh = kwargs.pop('fresh_login', True)
super(_FlaskLoginClient, self).__init__(*args, **kwargs)
with self.session_transaction() as sess:
if user:
se... |
def test_check_credits(skip_qtbot, preset_manager):
base = preset_manager.default_preset_for_game(RandovaniaGame.METROID_PRIME).get_preset()
preset = dataclasses.replace(base, uuid=uuid.UUID('b41fde84-1f57-4b79-8cd6-3e5a78077fa6'))
options = MagicMock()
editor = PresetEditor(preset, options)
window ... |
class RecvFL2SendRTL(Component):
def recv(s, msg):
while (s.entry is not None):
greenlet.getcurrent().parent.switch(0)
s.entry = msg
def construct(s, MsgType):
s.recv = RecvIfcFL(method=s.recv)
s.send = SendIfcRTL(MsgType)
s.entry = None
def up_clear()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.