code stringlengths 281 23.7M |
|---|
class ModelBuilder(nn.Module):
def __init__(self):
super(ModelBuilder, self).__init__()
self.backbone = get_backbone(cfg.BACKBONE.TYPE, **cfg.BACKBONE.KWARGS)
if cfg.ADJUST.ADJUST:
self.neck = get_neck(cfg.ADJUST.TYPE, **cfg.ADJUST.KWARGS)
self.rpn_head = get_rpn_head(cfg... |
def test_plugin_interface(testdir):
testdir.makeconftest('\n import pytest\n\n .tryfirst\n def pytest_timeout_set_timer(item, settings):\n print()\n print("pytest_timeout_set_timer")\n return True\n\n .tryfirst\n def pytest_timeout_cancel_timer(item):\n print()\n ... |
class TestSummaryWriterWithUpdater(unittest.TestCase):
def setUp(self):
self.tmp_dir = tempfile.mkdtemp()
writer = tensorboardX.SummaryWriter(log_dir=self.tmp_dir)
self.writer = SummaryWriterWithUpdater(writer=writer)
def test_init(self):
assert hasattr(self.writer, 'setup')
... |
class Nut(Object):
file_path = String.T(optional=True)
file_format = String.T(optional=True)
file_mtime = Timestamp.T(optional=True)
file_size = Int.T(optional=True)
file_segment = Int.T(optional=True)
file_element = Int.T(optional=True)
kind_id = Int.T()
codes = Codes.T()
tmin_secon... |
def build_lr_scheduler(optimizer, optim_cfg):
lr_scheduler = optim_cfg.LR_SCHEDULER
stepsize = optim_cfg.STEPSIZE
gamma = optim_cfg.GAMMA
max_epoch = optim_cfg.MAX_EPOCH
if (lr_scheduler not in AVAI_SCHEDS):
raise ValueError('Unsupported scheduler: {}. Must be one of {}'.format(lr_scheduler,... |
class QtNetworkClient(QtCore.QObject, NetworkClient):
Connect = Signal()
ConnectError = Signal()
Disconnect = Signal()
UserChanged = Signal(User)
ConnectionStateUpdated = Signal(ConnectionState)
MultiplayerSessionMetaUpdated = Signal(MultiplayerSessionEntry)
MultiplayerSessionActionsUpdated ... |
class QlTimerPeripheral(QlPeripheral):
def __init__(self, ql: Qiling, label: str):
super().__init__(ql, label)
self._ratio = 1
def set_ratio(self, ratio):
self._ratio = ratio
def ratio(self):
return self._ratio
def ratio(self, value):
self.set_ratio(value)
def... |
def download_individual_checkpoint_dataset(dataset_path):
dataset_name = process_dset_name(dataset_path)
dataset_dir = os.path.dirname(dataset_path)
if ((not os.path.isdir(dataset_path)) and is_main_proc()):
os.makedirs(dataset_dir, exist_ok=True)
web_path = f'
download_and_extract_a... |
def _expand_number(m):
num = int(m.group(0))
if ((num > 1000) and (num < 3000)):
if (num == 2000):
return 'two thousand'
elif ((num > 2000) and (num < 2010)):
return ('two thousand ' + _inflect.number_to_words((num % 100)))
elif ((num % 100) == 0):
ret... |
class TestLogging():
def test_log_dont_call_build_msg(self):
with mock.patch('pymodbus.logging.Log.build_msg') as build_msg_mock:
Log.setLevel(logging.INFO)
Log.debug('test')
build_msg_mock.assert_not_called()
Log.setLevel(logging.DEBUG)
Log.debug(... |
def assign_scores(question: HotpotQuestion):
question_spvec = PROCESS_RANKER.text2spvec(question.question_tokens, tokenized=True)
paragraphs = [flatten_iterable(par.sentences) for par in (question.supporting_facts + question.distractors)]
pars_spvecs = [PROCESS_RANKER.text2spvec(x, tokenized=True) for x in ... |
def output_clauses(format, clauses):
if (checkSetting(format, 'output_is_binary') and hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()):
print('This is a binary format - not writing to terminal.\nPlease direct output to a file or pipe.')
return
clause_sep = checkSetting(format, 'clause_sepa... |
class BaseDistance():
def distance(x: Tensor, y: Tensor) -> Tensor:
raise NotImplementedError
def similarity(x: Tensor, y: Tensor) -> Tensor:
raise NotImplementedError
def distance_matrix(x: Tensor, y: Optional[Tensor]=None) -> Tensor:
raise NotImplementedError
def similarity_mat... |
def get_stat_struct(ql: Qiling):
if (ql.os.type == QL_OS.FREEBSD):
if ((ql.arch.type == QL_ARCH.X8664) or (ql.arch.bits == 64)):
return FreeBSDX8664Stat()
else:
return FreeBSDX86Stat()
elif (ql.os.type == QL_OS.MACOS):
return MacOSStat()
elif (ql.os.type == QL... |
class RPNTestMixin(object):
if (sys.version_info >= (3, 7)):
async def async_simple_test_rpn(self, x, img_metas):
sleep_interval = self.test_cfg.pop('async_sleep_interval', 0.025)
async with completed(__name__, 'rpn_head_forward', sleep_interval=sleep_interval):
rpn_o... |
class TestNetCDF4FileHandler(unittest.TestCase):
def setUp(self):
from netCDF4 import Dataset
with Dataset('test.nc', 'w') as nc:
nc.createDimension('rows', 10)
nc.createDimension('cols', 100)
g1 = nc.createGroup('test_group')
ds1_f = g1.createVariable... |
class MoveFileDialog(QDialog):
new_infos = pyqtSignal(object)
def __init__(self, parent=None):
super(MoveFileDialog, self).__init__(parent)
self.infos = None
self.dirs = {}
self.initUI()
self.setStyleSheet(dialog_qss_style)
def update_ui(self):
names = '\n'.jo... |
class GLWidget(QOpenGLWidget):
clicked = pyqtSignal()
(PROGRAM_VERTEX_ATTRIBUTE, PROGRAM_TEXCOORD_ATTRIBUTE) = range(2)
vsrc = '\nattribute highp vec4 vertex;\nattribute mediump vec4 texCoord;\nvarying mediump vec4 texc;\nuniform mediump mat4 matrix;\nvoid main(void)\n{\n gl_Position = matrix * vertex;\n... |
class Describe_TiffParser():
def it_can_parse_the_properties_from_a_tiff_stream(self, stream_, _make_stream_reader_, _IfdEntries_, ifd0_offset_, stream_rdr_, _TiffParser__init_, ifd_entries_):
tiff_parser = _TiffParser.parse(stream_)
_make_stream_reader_.assert_called_once_with(stream_)
_Ifd... |
class lck_grp_rw_stat_t(ctypes.Structure):
_fields_ = (('lck_grp_rw_util_cnt', ctypes.c_uint64), ('lck_grp_rw_held_cnt', ctypes.c_uint64), ('lck_grp_rw_miss_cnt', ctypes.c_uint64), ('lck_grp_rw_wait_cnt', ctypes.c_uint64), ('lck_grp_rw_held_max', ctypes.c_uint64), ('lck_grp_rw_held_cum', ctypes.c_uint64), ('lck_grp... |
class RLAgent(object):
def __init__(self, config, word_vocab, verb_map, noun_map, replay_memory_capacity=100000, replay_memory_priority_fraction=0.0, load_pretrained=False):
self.use_dropout_exploration = True
self.config = config
self.use_cuda = config['general']['use_cuda']
self.wo... |
def char_embedding(inputs, voca_size, embedding_dim, length, charMaxLen, initializer=None, reuse=False, trainable=True, scope='EmbeddingChar'):
if (initializer == None):
initializer = np.concatenate((np.zeros((1, embedding_dim), dtype='float32'), np.random.rand((voca_size - 1), embedding_dim).astype('float3... |
class YamlExtension(Extension):
def filter_stream(self, stream):
while (not stream.eos):
token = next(stream)
if token.test('variable_begin'):
var_expr = []
while (not token.test('variable_end')):
var_expr.append(token)
... |
class AggregatedNode(Loadable, Drawable, _core.AggregatedNode, metaclass=NodeMeta):
__parameter_attributes__ = ('factors', 'min_flow', 'max_flow')
__node_attributes__ = ('nodes',)
def __init__(self, model, name, nodes, flow_weights=None, **kwargs):
super(AggregatedNode, self).__init__(model, name, *... |
def combine_registries(registries):
global_options = {}
traversals = {}
cli_functions = {}
commands = {}
for registry in registries:
traversals.update(registry.traversals)
global_options.update(registry.global_options)
cli_functions.update(registry.cli_functions)
comm... |
_profiler_printer
def profile_printer(message, compile_time, fct_call_time, apply_time, apply_cimpl, outputs_size, file):
if any(((isinstance(node.op, Scan) and (v > 0)) for ((fgraph, node), v) in apply_time.items())):
print('', file=file)
print('Scan overhead:', file=file)
print('<Scan op t... |
class Vgg16PerceptualLoss(torch.nn.Module):
def __init__(self, perceptual_indices=[1, 3, 6, 8, 11, 13, 15, 18, 20, 22], loss_func='l1', requires_grad=False):
super(Vgg16PerceptualLoss, self).__init__()
vgg_pretrained_features = models.vgg16(pretrained=True).features.eval()
max_layer_idx = ma... |
class Context(commands.Context['commands.Bot'], Generic[BotT]):
if TYPE_CHECKING:
from .Bot import Quotient
bot: Quotient
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
def db(self):
return self.bot.db
def session(self) -> aio
... |
def deprecated(msg=None, stacklevel=2):
def deprecated_dec(fn):
(fn)
def wrapper(*args, **kwargs):
warnings.warn((msg or ('Function %s is deprecated.' % fn.__name__)), category=DeprecationWarning, stacklevel=stacklevel)
return fn(*args, **kwargs)
return wrapper
re... |
class TestPolyText8(EndianTest):
def setUp(self):
self.req_args_0 = {'drawable': , 'gc': , 'items': [{'delta': 2, 'string': 'zoo'}, , {'delta': 0, 'string': 'ie'}], 'x': (- 11315), 'y': (- 22209)}
self.req_bin_0 = b'J\x00\x08\x00\xf3\xf0=J\x12\x16\xa8M\xcd\xd3?\xa9\x03\x02zoo\xff\x01\x02\x03\x04\x02... |
def matrix_transposed_to_hex_values(matrix, font_width, font_height):
hex_values = []
width_hex = ('0x' + format(font_width, '02X'))
hex_values.append(width_hex)
for col in range(font_width):
for row in range(0, font_height, 8):
pixel_group = [matrix[r][col] for r in range(row, (row ... |
def urljoin_parts(base_parts, reference_parts):
(scheme, authority, path, query, fragment) = base_parts
(rscheme, rauthority, rpath, rquery, rfragment) = reference_parts
if (rscheme == scheme):
rscheme = None
if (rscheme is not None):
(tscheme, tauthority, tpath, tquery) = (rscheme, raut... |
def main():
opt = parse_option()
set_seed(opt.seed)
if opt.use_tb:
logger = tb_logger.Logger(logdir=opt.tb_folder, flush_secs=2)
train_partition = ('trainval' if opt.use_trainval else 'train')
(train_loader, val_loader, n_cls) = get_train_loaders(opt, train_partition)
opt.n_cls = n_cls
... |
_sentencepiece
_tokenizers
_torch
class SqueezeBertModelIntegrationTest(unittest.TestCase):
def test_inference_classification_head(self):
model = SqueezeBertForSequenceClassification.from_pretrained('squeezebert/squeezebert-mnli')
input_ids = torch.tensor([[1, 29414, 232, 328, 740, 1140, 12695, 69, ... |
def generate_3_regular_problem(task: ThreeRegularProblemGenerationTask, base_dir=None):
if (base_dir is None):
base_dir = DEFAULT_BASE_DIR
if recirq.exists(task, base_dir=base_dir):
print(f'{task.fn} already exists. Skipping.')
return
problem = _get_all_3_regular_problems()[(task.n_q... |
def convert_remote_files_to_fsspec(filenames, storage_options=None):
if (storage_options is None):
storage_options = {}
if isinstance(filenames, dict):
return _check_file_protocols_for_dicts(filenames, storage_options)
return _check_file_protocols(filenames, storage_options) |
def test__torque_driven_ocp__multi_biorbd_model():
from bioptim.examples.torque_driven_ocp import example_multi_biorbd_model as ocp_module
bioptim_folder = os.path.dirname(ocp_module.__file__)
ocp_module.prepare_ocp(biorbd_model_path=(bioptim_folder + '/models/triple_pendulum.bioMod'), biorbd_model_path_mod... |
class Effect6472(BaseEffect):
dealsDamage = True
type = 'active'
def handler(fit, mod, context, projectionRange, **kwargs):
fit.ship.boostItemAttr('maxVelocity', mod.getModifiedItemAttr('speedFactor'), stackingPenalties=True, **kwargs)
fit.ship.increaseItemAttr('warpScrambleStatus', mod.getM... |
def get_scene_graph(image_id, images='data/', image_data_dir='data/by-id/', synset_file='data/synsets.json'):
if (type(images) is str):
images = {img.id: img for img in get_all_image_data(images)}
fname = (str(image_id) + '.json')
image = images[image_id]
data = json.load(open(osp.join(image_dat... |
class DmaAllocator(Allocator):
def __init__(self):
super().__init__()
self.dmaHeap = DmaHeap()
self.mapped_buffers = {}
self.mapped_buffers_used = {}
self.frame_buffers = {}
self.open_fds = []
self.libcamera_fds = []
self.sync = self.DmaSync
def al... |
def transform_while_stmt(builder: IRBuilder, s: WhileStmt) -> None:
(body, next, top, else_block) = (BasicBlock(), BasicBlock(), BasicBlock(), BasicBlock())
normal_loop_exit = (else_block if (s.else_body is not None) else next)
builder.push_loop_stack(top, next)
builder.goto_and_activate(top)
proces... |
def put_stream(up_token, key, input_stream, file_name, data_size, hostscache_dir=None, params=None, mime_type=None, progress_handler=None, upload_progress_recorder=None, modify_time=None, keep_last_modified=False, part_size=None, version='v1', bucket_name=None, metadata=None):
if (not bucket_name):
bucket_n... |
.parametrize('dims, spec, expect', [(('dim',), ('dim',), [[0]]), (('dim0', 'dim1'), ('dim0', 'dim1'), [[0, 1]]), (('dim0', 'dim1'), ('dim0', '*'), [[0, 1]]), (('dim0', 'dim1'), ('*', '*'), [[0, 1]]), (('dim0', 'dim1'), ({'dim0', None}, {'dim1', None}), [[0, 1]]), (('dim0', 'dim1'), ({'*', None}, {'*', None}), [[0, 1]])... |
((sys.version_info < (3, 9, 0)), 'Requires newer python')
def test_scoped_addresses_from_cache():
type_ = '_
registration_name = f'scoped.{type_}'
zeroconf = r.Zeroconf(interfaces=['127.0.0.1'])
host = 'scoped.local.'
zeroconf.cache.async_add_records([r.DNSPointer(type_, const._TYPE_PTR, (const._CLA... |
class Texture():
def __init__(self, name, search_path):
self._options = TextureOptionsParser(name).parse()
self._name = self._options.name
self._search_path = Path(search_path)
self._path = Path(search_path, self._name)
self.image = None
def name(self):
return sel... |
def format_error(error, tb=None):
if (error is None):
return None
result = ''
if (hasattr(error, '_traceback') or (tb is not None)):
tb = (tb or error._traceback)
tb_list = traceback.format_exception(error.__class__, error, tb)
elif isinstance(error, BaseException):
tb_li... |
class COp(Op, CLinkerOp):
def make_c_thunk(self, node: Apply, storage_map: StorageMapType, compute_map: ComputeMapType, no_recycling: Collection[Variable]) -> CThunkWrapperType:
import pytensor.link.c.basic
from pytensor.graph.fg import FunctionGraph
node_input_storage = [storage_map[r] for ... |
class FloatFieldTest(BaseFieldTestMixin, NumberTestMixin, FieldTestCase):
field_class = fields.Float
def test_defaults(self):
field = fields.Float()
assert (not field.required)
assert (field.__schema__ == {'type': 'number'})
def test_with_default(self):
field = fields.Float(d... |
.end_to_end()
def test_error_when_return_pytree_mismatch(runner, tmp_path):
source = '\n from pathlib import Path\n from typing import Any\n from typing_extensions import Annotated\n from pytask import PathNode\n\n node1 = PathNode(path=Path("file1.txt"))\n node2 = PathNode(path=Path("file2.txt"))... |
class CacheIndexable():
def __init__(self, indexed_iter, cache_size=None):
self.cache_size = cache_size
self.iter = indexed_iter
self.cache_dict = {}
self.cache_indices = []
def __next__(self):
next_elem = next(self.iter)
next_index = next_elem.index
self.... |
class Fixed(NumberMixin, Raw):
def __init__(self, decimals=5, **kwargs):
super(Fixed, self).__init__(**kwargs)
self.precision = Decimal((('0.' + ('0' * (decimals - 1))) + '1'))
def format(self, value):
dvalue = Decimal(value)
if ((not dvalue.is_normal()) and (dvalue != ZERO)):
... |
def resize_pos_embed(posemb, posemb_new):
_logger.info('Resized position embedding: %s to %s', posemb.shape, posemb_new.shape)
seq_length_old = posemb.shape[2]
(num_blocks_new, seq_length_new) = posemb_new.shape[1:3]
size_new = int(math.sqrt((num_blocks_new * seq_length_new)))
posemb = deblockify(po... |
class TestValidSubsetsErrors(unittest.TestCase):
def _test_case(self, paths, extra_flags):
with tempfile.TemporaryDirectory() as data_dir:
[write_empty_file(os.path.join(data_dir, f'{p}.bin')) for p in (paths + ['train'])]
cfg = make_lm_config(data_dir, extra_flags=extra_flags)
... |
def call_wine_cmd_once(wine, cmd, env, mode):
p = run_subprocess((wine + cmd), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, close_fds=True, shell=False)
output = find_cmd_out(cmd)
error = None
if ((output is not None) and os.path.exists(output)):
try:
os.remove(output)
... |
_memoize(300)
def get_items_from_rss(rss_link: str, timeout=10) -> list[dict]:
logger.info(f'Get items from rss: {rss_link}')
rss_items = []
try:
response = make_get_request(rss_link)
if (not response):
return rss_items
res_news = feedparser.parse(response.content)
... |
def send_a_detailed_product(update, context, product, pattern_identifier):
query = update.callback_query
markup = tamplate_for_show_a_detailed_product(pattern_identifier, context)
text = get_text_for_detailed_product(product, context)
query.message.edit_media(media=InputMediaPhoto(product.image_id, text... |
def assert_color(expected: bool, default: Optional[bool]=None) -> None:
file = io.StringIO()
if (default is None):
default = (not expected)
file.isatty = (lambda : default)
tw = terminalwriter.TerminalWriter(file=file)
assert (tw.hasmarkup is expected)
tw.line('hello', bold=True)
s =... |
def read_mapping_file(map_file) -> [MappingInfo]:
mappings = []
with open(map_file, 'r', encoding='utf-8', newline='') as f:
map_reader = csv.reader(f)
for row in map_reader:
if (len(row) > 2):
pattern = row[0].strip()
payee = row[1].strip()
... |
class NonBlockingLeaseTests(KazooLeaseTests):
def test_renew(self):
lease = self.client.NonBlockingLease(self.path, datetime.timedelta(seconds=3), utcnow=self.clock)
assert lease
assert (lease.obtained is True)
self.clock.forward(2)
renewed_lease = self.client.NonBlockingLeas... |
def get_feature_columns():
srcItem_cate1 = tf.feature_column.categorical_column_with_hash_bucket('FEA_SrcItemFirstCat', hash_bucket_size=128)
item_cate1 = tf.feature_column.categorical_column_with_hash_bucket('FEA_ItemFirstCat', hash_bucket_size=128)
srcItem_cate2 = tf.feature_column.categorical_column_with... |
class BaseTwRwEmbeddingSharding(EmbeddingSharding[(C, F, T, W)]):
def __init__(self, sharding_infos: List[EmbeddingShardingInfo], env: ShardingEnv, device: Optional[torch.device]=None, need_pos: bool=False, qcomm_codecs_registry: Optional[Dict[(str, QuantizedCommCodecs)]]=None) -> None:
super().__init__(qco... |
class VanillaBlock(nn.Sequential):
def __init__(self, width_in: int, width_out: int, stride: int, bn_epsilon: float, bn_momentum: float, activation: nn.Module, *args, **kwargs):
super().__init__()
self.a = nn.Sequential(nn.Conv2d(width_in, width_out, 3, stride=stride, padding=1, bias=False), nn.Batc... |
(is_windows(), 'unix only')
class TUnixRemote(TestCase):
def test_fifo(self):
mock = Mock()
remote = QuodLibetUnixRemote(None, mock)
remote._callback(b'foo\n')
remote._callback(b'bar\nbaz')
self.assertEqual(mock.lines, [bytes2fsn(b, None) for b in [b'foo', b'bar', b'baz']])
... |
.parametrize('username,password', users)
def test_update(db, client, username, password):
client.login(username=username, password=password)
instances = View.objects.all()
for instance in instances:
url = reverse(urlnames['detail'], args=[instance.pk])
data = {'uri_prefix': instance.uri_pref... |
def gather_results_from_each_node(num_replicas, save_dir, timeout) -> List[Dict[(str, List)]]:
start_wait = time.time()
logger.info('waiting for all nodes to finish')
json_data = None
while ((time.time() - start_wait) < timeout):
json_files = list(save_dir.glob('rank_*.json'))
if (len(js... |
def relabel(smiles, order=None):
if (order is None):
order = list(range(smiles.count('*')))
else:
order = [int(c) for c in order]
def add_isotope_tag_to_wildcard(m):
return ('[*:%d]' % ((order.pop(0) + 1),))
return _wildcard_pat.sub(add_isotope_tag_to_wildcard, smiles) |
class Migration(migrations.Migration):
dependencies = [('api', '0011_auto__1904')]
operations = [migrations.CreateModel(name='SpecialSnake', fields=[('name', models.CharField(max_length=140, primary_key=True, serialize=False)), ('info', models.TextField())], bases=(pydis_site.apps.api.models.mixins.ModelReprMix... |
def get_all_repo_users(namespace_name, repository_name):
return RepositoryPermission.select(User, Role, RepositoryPermission).join(User).switch(RepositoryPermission).join(Role).switch(RepositoryPermission).join(Repository).join(Namespace, on=(Repository.namespace_user == Namespace.id)).where((Namespace.username == ... |
def gather_logits(input_dir: Path, output_path: Optional[Path]=None, glob_pattern: str='logits-*.h5', verbose: bool=False):
if (output_path is None):
output_path = (input_dir / 'logits_gathered.h5')
input_files = list(input_dir.glob(glob_pattern))
with h5py.File(output_path, 'w') as output_file:
... |
def p_unary_expression(p):
if (len(p) == 2):
p[0] = p[1]
elif (p[1] == 'sizeof'):
if (p[2] == '('):
p[0] = SizeOfExpressionNode(p[3])
else:
p[0] = SizeOfExpressionNode(p[2])
elif (type(p[1]) == tuple):
p[0] = UnaryExpressionNode(p[1][0], p[1][1], p[2])... |
def gather_data(output_path, num_workers):
print('Start gathering data')
for dirname in ('feats', 'masks', 'jsons'):
if (output_path / dirname).is_dir():
shutil.rmtree((output_path / dirname))
(output_path / dirname).mkdir()
for dirname in ('feats', 'masks', 'jsons'):
for... |
class ChangeSignatureTest(unittest.TestCase):
def setUp(self):
super().setUp()
self.project = testutils.sample_project()
self.pycore = self.project.pycore
self.mod = testutils.create_module(self.project, 'mod')
def tearDown(self):
testutils.remove_project(self.project)
... |
def broadcast_dist_samples_shape(shapes, size=None):
if (size is None):
broadcasted_shape = np.broadcast_shapes(*shapes)
if (broadcasted_shape is None):
raise ValueError('Cannot broadcast provided shapes {} given size: {}'.format(', '.join([f'{s}' for s in shapes]), size))
return... |
def test_popup_focus(manager):
manager.test_window('one')
start_wins = len(manager.backend.get_all_windows())
(success, msg) = manager.c.eval(textwrap.dedent('\n from libqtile.popup import Popup\n popup = Popup(self,\n x=0,\n y=0,\n width=self.current_screen.wi... |
class Dict(Object):
dummy_for = dict
class __T(TBase):
multivalued = dict
def __init__(self, key_t=Any.T(), content_t=Any.T(), *args, **kwargs):
TBase.__init__(self, *args, **kwargs)
assert isinstance(key_t, TBase)
assert isinstance(content_t, TBase)
... |
class BatchVisualizer(BaseController):
def __init__(self, config):
assert isinstance(config, dict)
config.setdefault('priority', 'MEDIUM')
super().__init__(config)
viz_keys = config.get('viz_keys', [])
if (not isinstance(viz_keys, (tuple, list))):
viz_keys = [viz_... |
def writePFM(file, image, scale=1):
file = open(file, 'wb')
color = None
if (image.dtype.name != 'float32'):
raise Exception('Image dtype must be float32.')
image = np.flipud(image)
if ((len(image.shape) == 3) and (image.shape[2] == 3)):
color = True
elif ((len(image.shape) == 2)... |
.parametrize('length, chunks, size, step', [(12, 6, 4, 4), (12, 6, 4, 2), (12, 5, 4, 4)])
.parametrize('dtype', [np.int64, np.float32, np.float64])
def test_moving_statistic_2d(length, chunks, size, step, dtype):
arr = np.arange((length * 3), dtype=dtype).reshape(length, 3)
def sum_cols(x):
return np.su... |
class Effect6327(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Missile Launcher Operation')), 'emDamage', src.getModifiedItemAttr('shipBonusCD1'), skill='Caldari Destroyer', **kwargs) |
def cook_refs(refs, eff=None, n=4):
reflen = []
maxcounts = {}
for ref in refs:
(rl, counts) = precook(ref, n)
reflen.append(rl)
for (ngram, count) in six.iteritems(counts):
maxcounts[ngram] = max(maxcounts.get(ngram, 0), count)
if (eff == 'shortest'):
reflen ... |
class Commands_Seen_TestCase(ParserTest):
def __init__(self, *args, **kwargs):
ParserTest.__init__(self, *args, **kwargs)
self.ks = '\nbootloader --location=none\npart / --size=10000 --fstype=ext4\n'
def runTest(self):
self.parser.readKickstartFromString(self.ks)
self.assertFalse... |
class UnetNoCond7DS(nn.Module):
def __init__(self, input_nc=3, output_nc=3, nf=64, up_mode='upconv', use_dropout=False, return_lowres=False, return_2branches=False):
super(UnetNoCond7DS, self).__init__()
assert (up_mode in ('upconv', 'upsample'))
self.return_lowres = return_lowres
se... |
class Data2VecVisionOnnxConfig(OnnxConfig):
torch_onnx_minimum_version = version.parse('1.11')
def inputs(self) -> Mapping[(str, Mapping[(int, str)])]:
return OrderedDict([('pixel_values', {0: 'batch', 1: 'sequence'})])
def atol_for_validation(self) -> float:
return 0.0001 |
def compare_proposer_levels(x, y):
print('Proposers diff')
for (idx, l, r) in compare_list(x['proposer_levels'], y['proposer_levels']):
if (l is None):
l = []
if (r is None):
r = []
l_ = [x[(- 6):] for x in set(l).difference(set(r))]
r_ = [x[(- 6):] for x ... |
class TestPreallocatedOutput():
def setup_method(self):
self.rng = np.random.default_rng(seed=utt.fetch_seed())
def test_f_contiguous(self):
a = fmatrix('a')
b = fmatrix('b')
z = BrokenCImplementationAdd()(a, b)
out = dot(z, np.eye(7))
a_val = self.rng.standard_no... |
def register(name: Optional[str]=None) -> Callable[([_T], _T)]:
def wrapper(fn: _T) -> _T:
fn_name = (fn.__name__ if (name is None) else name)
if (sys.version_info < (3, 9)):
log.misc.vdebug("debugcachestats not supported on python < 3.9, not adding '%s'", fn_name)
return fn
... |
class ResBasicBlock(nn.Module):
def __init__(self, w_in, w_out, stride, bn_norm, bm=None, gw=None, se_r=None):
assert ((bm is None) and (gw is None) and (se_r is None)), 'Basic transform does not support bm, gw, and se_r options'
super(ResBasicBlock, self).__init__()
self.construct(w_in, w_o... |
def get_formatted_filename(reports_title, date: datetime, extension: str):
str_date = date.strftime('%Y_%m_%d-%H%M')
filename = '{str_date:s} {reports_title:s}.{extension:s}'.format(str_date=str_date, reports_title=reports_title, extension=extension)
filename = filename.replace(' ', '_')
return filename |
class ApplicationAppearanceManager(GetWithoutIdMixin, UpdateMixin, RESTManager):
_path = '/application/appearance'
_obj_cls = ApplicationAppearance
_update_attrs = RequiredOptional(optional=('title', 'description', 'logo', 'header_logo', 'favicon', 'new_project_guidelines', 'header_message', 'footer_message... |
.parametrize('tensor', [torch.rand(2, 3, 4, 5), torch.rand(2, 3, 4, 5, 6)])
.parametrize('index1', [slice(None), slice(0, 1), 0, [0], [0, 1], np.arange(2), torch.arange(2), [True, True], Ellipsis])
.parametrize('index2', [slice(None), slice(1, 3, 1), slice((- 3), (- 1)), 0, [0], [0, 1], np.arange(0, 1), torch.arange(2)... |
class QueryType(click.ParamType):
name = 'SMILES'
def convert(self, value, param, ctx):
if (not isinstance(value, str)):
return value
try:
(mol, frags) = parse_smiles_then_fragment(value)
if (len(frags) != 1):
raise MolProcessingError('Query/va... |
def limit_to_gamut(xy: ColorXY, gamut: ColorGamut) -> ColorXY:
(r, g, b) = gamut
if (not is_same_side(xy, r, g, b)):
xy = closest_point(xy, g, b)
if (not is_same_side(xy, g, b, r)):
xy = closest_point(xy, b, r)
if (not is_same_side(xy, b, r, g)):
xy = closest_point(xy, r, g)
... |
class PassportElementErrorFiles(PassportElementError):
__slots__ = ('_file_hashes',)
def __init__(self, type: str, file_hashes: List[str], message: str, *, api_kwargs: Optional[JSONDict]=None):
super().__init__('files', type, message, api_kwargs=api_kwargs)
with self._unfrozen():
sel... |
def main():
parser = argparse.ArgumentParser(description='Global State Evaluation : StarCraft II')
parser.add_argument('--name', type=str, default='StarCraft II:TvT[BuildOrder:Spatial]', help='Experiment name. All outputs will be stored in checkpoints/[name]/')
parser.add_argument('--replays_path', default=... |
class _Layers():
def __init__(self, modules: Dict[(str, nn.Module)]) -> None:
self._modules = modules
def __contains__(self, name: str) -> bool:
return (name in self._modules)
def __len__(self) -> int:
return len(self._modules)
def _names(self) -> Tuple[(str, ...)]:
retur... |
_config
def test_hammer_ratio_tile(manager):
manager.c.next_layout()
for i in range(7):
manager.test_window('one')
for i in range(30):
manager.c.to_screen(((i + 1) % 4))
manager.c.group['a'].toscreen()
assert (manager.c.group['a'].info()['windows'] == ['one', 'one', 'one', 'one',... |
class BaseConfig(object):
name = None
hint = None
info = None
int_type = IntegerParamType()
float_type = FloatParamType()
bool_type = BooleanParamType()
index_type = IndexParamType()
json_type = JsonParamType()
list_type = ListParamType()
command_option = cloup.option
def ins... |
class PieChart(QQuickPaintedItem):
chartCleared = pyqtSignal()
(str)
def name(self):
return self._name
def name(self, name):
self._name = name
(QColor)
def color(self):
return self._color
def color(self, color):
self._color = QColor(color)
def __init__(sel... |
(frozen=True)
class CorruptionCosmeticPatches(BaseCosmeticPatches):
random_door_colors: bool = False
random_welding_colors: bool = False
player_suit: CorruptionSuit = CorruptionSuit.VARIA
def default(cls) -> CorruptionCosmeticPatches:
return cls()
def game(cls) -> RandovaniaGame:
ret... |
class MetaAconC(nn.Module):
def __init__(self, c1, k=1, s=1, r=16):
super().__init__()
c2 = max(r, (c1 // r))
self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True)
self.fc2 = nn.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.