code stringlengths 281 23.7M |
|---|
def map_dict_keys(inputs, keys_map, logger_print=None):
from .string_utils import regex_replace, regex_match, is_regex
import re
outputs = {}
for (key, value) in inputs.items():
new_key = key
for (in_pattern, out_pattern) in keys_map.items():
if regex_match(key, in_pattern):
... |
class Adam(torch.optim.Optimizer):
def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False):
defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, amsgrad=amsgrad)
super(Adam, self).__init__(params, defaults)
def supports_memory_efficie... |
class CmdTrade(Command):
key = 'trade'
aliases = ['barter']
locks = 'cmd:all()'
help_category = 'General'
def func(self):
if (not self.args):
if (self.caller.ndb.tradehandler and self.caller.ndb.tradeevent.trade_started):
self.caller.msg("You are already in a trad... |
def resize_images_bilinear(X, height_factor=1, width_factor=1, target_height=None, target_width=None, data_format='default'):
if (data_format == 'default'):
data_format = K.image_data_format()
if (data_format == 'channels_first'):
original_shape = K.int_shape(X)
if (target_height and tar... |
def test_collect_symlink_out_of_tree(pytester: Pytester) -> None:
sub = pytester.mkdir('sub')
real = sub.joinpath('test_real.py')
real.write_text(textwrap.dedent('\n def test_nodeid(request):\n # Should not contain sub/ prefix.\n assert request.node.nodeid == "test_real.py::test... |
(tryfirst=True)
def pytest_runtest_call(item: Item) -> None:
try:
request = item._request
except AttributeError:
return
factoryboy_request = request.getfixturevalue('factoryboy_request')
factoryboy_request.evaluate(request)
assert (not factoryboy_request.deferred)
request.config.... |
def series_filter(values, kernel_size=3):
filter_values = np.cumsum(values, dtype=float)
filter_values[kernel_size:] = (filter_values[kernel_size:] - filter_values[:(- kernel_size)])
filter_values[kernel_size:] = (filter_values[kernel_size:] / kernel_size)
for i in range(1, kernel_size):
filter_... |
class Effect6574(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
lvl = src.level
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Capital Railgun Specialization')), 'damageMultiplier', (src.getModifiedItemAttr('damageMultiplierBonus') * ... |
def prepare_parser():
usage = 'Parser for ImageNet HDF5 scripts.'
parser = ArgumentParser(description=usage)
parser.add_argument('--dataset', type=str, default='I128', help='Which Dataset to train on, out of I128, I256, C10, C100;Append "_hdf5" to use the hdf5 version for ISLVRC (default: %(default)s)')
... |
def nodes_to_html(nodes):
out = []
append = out.append
stack = []
curr = nodes
i = (- 1)
while True:
i += 1
if (i >= len(curr)):
if (not stack):
break
(curr, i) = stack.pop()
append(f"</{curr[i]['tag']}>")
continue
... |
('randovania.cli._run_args', autospec=True)
('randovania.cli._create_parser', autospec=True)
def test_run_cli(mock_create_parser: MagicMock, mock_run_args: MagicMock):
argv = [MagicMock(), MagicMock(), MagicMock()]
mock_run_args.return_value = 1234
with pytest.raises(SystemExit) as p:
cli.run_cli(ar... |
def simclr_train(train_loader, model, criterion, optimizer, epoch):
losses = AverageMeter('Loss', ':.4e')
progress = ProgressMeter(len(train_loader), [losses], prefix='Epoch: [{}]'.format(epoch))
model.train()
for (i, batch) in enumerate(train_loader):
images = batch['image']
images_augm... |
('iM_product_vect_jvp_vjp_translation')
def _iM_product_vect_jvp_vjp_translation(c, cotan, q, vect, q_tan, vect_tan):
(type_in, size_xla, dims_spec) = check_dim_imputs((cotan, q, vect, q_tan, vect_tan), c)
op_name = (b'iM_prod_vect_jvp_vjp_wrapper_f32' if (type_in == np.float32) else b'iM_prod_vect_jvp_vjp_wrap... |
def run_locking_test(ctx):
with tempfile.TemporaryDirectory() as dir_name:
assert (get_subprocess_lock_state(ctx, dir_name) == 'unlocked')
with lock_ctx(dir_name):
dir_key = f'{dir_name}-{os.getpid()}'
assert (dir_key in local_mem._locks)
assert local_mem._locks[d... |
def log(header, data, level=None):
if (logfile is None):
return
if (level is not None):
log_level_set(level)
if (not isinstance(data, str)):
data = pp.pformat(data)
if len(header):
logfile.write((('\n' + log_get_sec()) + ' '))
logfile.write(header)
if (len(hea... |
def subparser_call(self, parser, namespace, values, option_string=None):
from argparse import ArgumentError, SUPPRESS, _UNRECOGNIZED_ARGS_ATTR
parser_name = values[0]
arg_strings = values[1:]
if (self.dest is not SUPPRESS):
setattr(namespace, self.dest, parser_name)
try:
parser = sel... |
_rewriter([IfElse])
def find_measurable_ifelse_mixture(fgraph, node):
rv_map_feature: Optional[PreserveRVMappings] = getattr(fgraph, 'preserve_rv_mappings', None)
if (rv_map_feature is None):
return None
op = node.op
(if_var, *base_rvs) = node.inputs
valued_rvs = rv_map_feature.rv_values.key... |
def gen_char_embedding(pretrained_char_embedding_file=None, gram_dict=None, embedding_dim=300, output_file=None):
if (not os.path.exists(output_file)):
word2vec = gensim.models.KeyedVectors.load_word2vec_format(pretrained_char_embedding_file, binary=False, unicode_errors='ignore')
text_wordvec = np.... |
class mixed_pdf(PDF):
def __init__(self, shape, pdf1, pdf2, pdf1_weight=0.5):
self.pdf1_weight = pdf1_weight
self.pdf2_weight = (1.0 - pdf1_weight)
self.shape = shape
self.pdf1 = pdf1
self.pdf2 = pdf2
def value(self, ray_dir):
return ((self.pdf1.value(ray_dir) * s... |
def _get_asyncio_mode(config: Config) -> Mode:
val = config.getoption('asyncio_mode')
if (val is None):
val = config.getini('asyncio_mode')
try:
return Mode(val)
except ValueError:
modes = ', '.join((m.value for m in Mode))
raise pytest.UsageError(f'{val!r} is not a valid... |
def main():
try:
pathserv = fs.get_path_info_for_active_session()
except mpexceptions.ExceptionUndefinedSamplesDir:
print("The env var 'pyglet_mp_samples_dir' is not defined.")
return 1
except mpexceptions.ExceptionNoSessionIsActive:
print('*** Error, no session active.')
... |
.parametrize('test_input, expected', [('1', '1st'), ('2', '2nd'), ('3', '3rd'), ('4', '4th'), ('11', '11th'), ('12', '12th'), ('13', '13th'), ('101', '101st'), ('102', '102nd'), ('103', '103rd'), ('111', '111th'), ('something else', 'something else'), (None, 'None'), (math.nan, 'NaN'), (math.inf, '+Inf'), ((- math.inf)... |
(ScheduleItem)
class ScheduleItemAdmin(admin.ModelAdmin):
list_display = ('title', 'conference', 'status', 'language', 'slot', 'type', 'submission')
list_filter = ('conference', 'status', 'type')
ordering = ('conference', 'slot')
form = ScheduleItemAdminForm
fieldsets = ((_('Event'), {'fields': ('co... |
class UpdateSponsorInfoViewTests(TestCase):
def setUp(self):
self.user = baker.make(settings.AUTH_USER_MODEL)
self.client.force_login(self.user)
self.sponsorship = baker.make(Sponsorship, submited_by=self.user, status=Sponsorship.APPLIED, _fill_optional=True)
self.sponsor = self.spon... |
_fixtures(WebFixture)
def test_html5_page(web_fixture):
fixture = web_fixture
widget = HTML5Page(fixture.view, title='It: $current_title')
widget.add_default_slot('slot1', P.factory())
tester = WidgetTester(widget)
rendered_html = tester.render_html()
head = ('<head><title>It: %s</title></head>'... |
def _make_xunit_fixture(obj: type, setup_name: str, teardown_name: str, cleanup_name: Optional[str], scope: Scope, pass_self: bool):
setup = getattr(obj, setup_name, None)
teardown = getattr(obj, teardown_name, None)
if ((setup is None) and (teardown is None)):
return None
if cleanup_name:
... |
def pytest_terminal_summary(terminalreporter: TerminalReporter) -> None:
if (terminalreporter.config.option.pastebin != 'failed'):
return
if ('failed' in terminalreporter.stats):
terminalreporter.write_sep('=', 'Sending information to Paste Service')
for rep in terminalreporter.stats['fa... |
.parametrize('state_index', [0, 10, 40])
.parametrize('history_steps', [0, 5, 10])
.parametrize('future_steps', [0, 5, 10])
def test_get_agent_context(zarr_dataset: ChunkedDataset, state_index: int, history_steps: int, future_steps: int) -> None:
scene = zarr_dataset.scenes[0]
frames = zarr_dataset.frames[get_f... |
class DataProvider(BaseDataProvider):
def __init__(self, dataset: typing.Union[(str, list, pd.DataFrame)], data_preprocessors: typing.List[typing.Callable]=None, batch_size: int=4, shuffle: bool=True, initial_epoch: int=1, augmentors: typing.List[Augmentor]=None, transformers: typing.List[Transformer]=None, batch_p... |
def run_tests(tests, xserver=True):
if (not xserver):
vt = 1
else:
vt = 7
if (os.system(f'sudo chvt {vt}') != 0):
print('FAILED to switch VT')
return len(tests)
time.sleep(3)
num_failed = 0
for test in tests:
clean_directory()
print('Running ', tes... |
def train(start_epoch):
global EPOCH_CNT
min_loss = .0
loss = 0
for epoch in range(start_epoch, MAX_EPOCH):
EPOCH_CNT = epoch
log_string(('**** EPOCH %03d ****' % epoch))
log_string(('Current learning rate: %f' % get_current_lr(epoch)))
log_string(('Current BN decay momen... |
.unit()
def test_module_name_from_path(tmp_path: Path) -> None:
result = _module_name_from_path((tmp_path / 'src/project/task_foo.py'), tmp_path)
assert (result == 'src.project.task_foo')
result = _module_name_from_path(Path('/home/foo/task_foo.py'), Path('/bar'))
assert (result == 'home.foo.task_foo')
... |
_module()
class NASFCOSHead(FCOSHead):
def _init_layers(self):
dconv3x3_config = dict(type='DCNv2', kernel_size=3, use_bias=True, deform_groups=2, padding=1)
conv3x3_config = dict(type='Conv', kernel_size=3, padding=1)
conv1x1_config = dict(type='Conv', kernel_size=1)
self.arch_confi... |
_test
def test_global_maxpooling2d_legacy_interface():
old_layer = keras.layers.GlobalMaxPooling2D(dim_ordering='tf', name='global_maxpool2d')
new_layer = keras.layers.GlobalMaxPool2D(data_format='channels_last', name='global_maxpool2d')
assert (json.dumps(old_layer.get_config()) == json.dumps(new_layer.get... |
class Class(PyCollector):
def from_parent(cls, parent, *, name, obj=None, **kw):
return super().from_parent(name=name, parent=parent, **kw)
def newinstance(self):
return self.obj()
def collect(self) -> Iterable[Union[(nodes.Item, nodes.Collector)]]:
if (not safe_getattr(self.obj, '__... |
class SigmoidFocalLoss(nn.Module):
def __init__(self, gamma, alpha):
super(SigmoidFocalLoss, self).__init__()
self.gamma = gamma
self.alpha = alpha
def forward(self, logits, targets):
assert logits.is_cuda
loss = sigmoid_focal_loss(logits, targets, self.gamma, self.alpha)... |
(frozen=True, slots=True)
class ConfigurableNode(Node):
def __repr__(self) -> str:
return f'ConfigurableNode({self.name!r})'
def requirement_to_leave(self, context: NodeContext) -> Requirement:
return context.patches.configurable_nodes[context.node_provider.identifier_for_node(self)] |
class BosonOperatorTest(unittest.TestCase):
def test_is_normal_ordered_empty(self):
op = (BosonOperator() * 2)
self.assertTrue(op.is_normal_ordered())
def test_is_normal_ordered_number(self):
op = (BosonOperator('2^ 2') * (- 1j))
self.assertTrue(op.is_normal_ordered())
def te... |
('/rename_subnet', methods=['POST'])
_params([dict(name='old_region', type=str, required=True, nullable=False), dict(name='new_region', type=str, required=True, nullable=False)], need_username=True)
_wrapper_json
_web_opration_log('rename_subnet', get_op_info=rename_subnet_log)
def rename_subnet(old_region, new_region,... |
class PyttiLocalConfigSearchPathPlugin(SearchPathPlugin):
def manipulate_search_path(self, search_path: ConfigSearchPath) -> None:
local_path = f'{os.getcwd()}/config/'
logger.debug(local_path)
search_path.append(provider='pytti_hydra_pathplugin', path=f'file://{local_path}') |
def _conv_flop_jit(inputs: Tuple[Any], outputs: Tuple[torch.Tensor]) -> Number:
x: torch.Tensor = inputs[0]
w: torch.Tensor = inputs[1]
(x_shape, w_shape, out_shape) = (x.shape, w.shape, outputs[0].shape)
transposed: bool = inputs[6]
return _conv_flop_count(list(x_shape), list(w_shape), list(out_sha... |
def parse_time(string: str, locale: ((Locale | str) | None)=LC_TIME, format: _PredefinedTimeFormat='medium') -> datetime.time:
numbers = re.findall('(\\d+)', string)
if (not numbers):
raise ParseError('No numbers were found in input')
format_str = get_time_format(format=format, locale=locale).patter... |
class AsmCmdShowElementCS(AsmCmdCheckable):
_id = 28
_menuText = QT_TRANSLATE_NOOP('asm3', 'Show element coordinate system')
_iconName = 'Assembly_ShowElementCS.svg'
_toolbarName = None
_menuGroupName = None
_contextMenuName = None
_saveParam = True
_defaultValue = False
def IsActive... |
class TestContextManagerModel():
def test_model(self) -> None:
ast_nodes = builder.extract_node('\n def test():\n "a"\n yield\n\n gen = test()\n gen.__enter__ #\n gen.__exit__ #\n ')
assert isinstance(ast_nodes, list)
enter = next(ast_no... |
class Updater():
def __init__(self, cnt_round, dic_agent_conf, dic_exp_conf, dic_traffic_env_conf, dic_path, best_round=None, bar_round=None):
self.cnt_round = cnt_round
self.dic_path = dic_path
self.dic_exp_conf = dic_exp_conf
self.dic_traffic_env_conf = dic_traffic_env_conf
... |
def compute_dense_reward(self, action, obs):
dist_to_handle = np.linalg.norm((self.robot.ee_position - self.obj1.position))
handle_goal_diff = np.linalg.norm((self.obj1.position - self.goal_position))
action_reg = np.sum(np.square(action))
w_dist = (- 1.0)
w_goal_diff = (- 1.0)
w_action_reg = (-... |
def fetch_versions(build_type, timeout=5.0):
try:
content = urlopen((' % build_type), timeout=timeout).read()
except Exception as error:
raise UpdateError(error) from error
d = feedparser.parse(content)
if d.bozo:
raise UpdateError(d.bozo_exception)
try:
link = d.feed... |
.parametrize('text', ('<a=b&b=a>', '<a=b|b=a>', '<a=b]b=a>'))
def test_compound_positive_matches(lexer, text):
assert (lexer.formula(0, text) == len(text))
assert (lexer.cur[0] == (0, Punctuation, '<'))
assert (lexer.cur[4][1] == Operator)
assert (lexer.cur[(- 1)] == ((len(text) - 1), Punctuation, '>')) |
def signature_test():
Print_Function()
e3d = Ga('e1 e2 e3', g=[1, 1, 1])
print('e3d.g =', e3d.g)
print('Signature = (3,0) I =', e3d.I(), ' I**2 =', (e3d.I() * e3d.I()))
e3d = Ga('e1 e2 e3', g=[2, 2, 2])
print('e3d.g =', e3d.g)
print('Signature = (3,0) I =', e3d.I(), ' I**2 =', (e3d.I() * e3d... |
def data_dir() -> Path:
if os.getenv('POETRY_HOME'):
return Path(os.getenv('POETRY_HOME')).expanduser()
if WINDOWS:
base_dir = Path(_get_win_folder('CSIDL_APPDATA'))
elif MACOS:
base_dir = Path('~/Library/Application Support').expanduser()
else:
base_dir = Path(os.getenv(... |
def test_legal_port_connect():
class A(ComponentLevel3):
def construct(s):
s.out = OutPort(32)
def up_A_write():
s.out = 123
class B(ComponentLevel3):
def construct(s):
s.in_ = InPort(32)
def up_B_read():
print(s.in_... |
class SDIO_STA(IntEnum):
CCRCFAIL = (1 << 0)
DCRCFAIL = (1 << 1)
CTIMEOUT = (1 << 2)
DTIMEOUT = (1 << 3)
TXUNDERR = (1 << 4)
RXOVERR = (1 << 5)
CMDREND = (1 << 6)
CMDSENT = (1 << 7)
DATAEND = (1 << 8)
STBITERR = (1 << 9)
DBCKEND = (1 << 10)
CMDACT = (1 << 11)
TXACT = ... |
class LastKnownValueEraser(TypeTranslator):
def visit_instance(self, t: Instance) -> Type:
if ((not t.last_known_value) and (not t.args)):
return t
return t.copy_modified(args=[a.accept(self) for a in t.args], last_known_value=None)
def visit_type_alias_type(self, t: TypeAliasType) -... |
def smiles2differentiable_graph(smiles):
mol = smiles2mol(smiles)
if (mol is None):
return None
if (not is_valid(smiles)):
return None
(idx_lst, node_mat, substructure_lst, atomidx_2substridx, adjacency_matrix, leaf_extend_idx_pair) = smiles2graph(smiles)
N = len(idx_lst)
d = len... |
.parametrize('string, separator, expected', [('a', '!', ['a']), ('ab', '!', ['ab']), ('ab!cd', '!', ['ab', 'cd']), ('ab!cd!ef', '!', ['ab', 'cd', 'ef']), ('a"b!c"d!ef', '!', ['a"b!c"d', 'ef']), ('a', '\\', ['a']), ('ab', '\\', ['ab']), ('ab\\cd', '\\', ['ab', 'cd']), ('ab\\cd\\ef', '\\', ['ab', 'cd', 'ef']), ('a"b\\c"d... |
class TransformerEncoderUnit(nn.Module):
def __init__(self, feat_dim, n_head=8, pos_en_flag=True, attn_type='softmax', P=None):
super(TransformerEncoderUnit, self).__init__()
self.feat_dim = feat_dim
self.attn_type = attn_type
self.pos_en_flag = pos_en_flag
self.P = P
... |
def get_hash():
if os.path.exists('.git'):
sha = get_git_hash()[:7]
elif os.path.exists(version_file):
try:
from basicsr.version import __version__
sha = __version__.split('+')[(- 1)]
except ImportError:
raise ImportError('Unable to get git version')
... |
class TestAttributes(unittest.TestCase):
def get_schema(self):
openldap_uri = 'file://{}'.format(TEST_SUBSCHEMA_FILES[0])
(dn, schema) = ldap.schema.urlfetch(openldap_uri)
return schema
def test_empty_attributetype_attrs(self):
attr = AttributeType('( 2.999 )')
self.asser... |
class FromImport(ImportInfo):
def __init__(self, module_name, level, names_and_aliases):
self.module_name = module_name
self.level = level
self.names_and_aliases = names_and_aliases
def get_imported_primaries(self, context):
if (self.names_and_aliases[0][0] == '*'):
m... |
class UserView(ModelView):
list_template = 'list.html'
can_create = False
can_delete = True
can_edit = False
def is_accessible(self):
return current_user.is_authenticated
def inaccessible_callback(self, name, **kwargs):
return redirect(url_for('admin.login_view', next=request.url... |
class SemAnalTypeInfoSuite(DataSuite):
required_out_section = True
files = ['semanal-typeinfo.test']
def run_case(self, testcase: DataDrivenTestCase) -> None:
try:
src = '\n'.join(testcase.input)
result = build.build(sources=[BuildSource('main', None, src)], options=get_seman... |
class Task():
def session_context(self):
_context.current_session = self.session
_context.current_task_id = self.coro_id
try:
(yield)
finally:
_context.current_session = None
_context.current_task_id = None
def gen_coro_id(coro=None):
n... |
.wrap
def get_block_sizes_runtime_device(block_sizes: List[int], runtime_device: torch.device, tensor_cache: Dict[(str, Tuple[(torch.Tensor, List[torch.Tensor])])], embedding_shard_metadata: Optional[List[List[int]]]=None, dtype: torch.dtype=torch.int32) -> Tuple[(torch.Tensor, List[torch.Tensor])]:
cache_key: str ... |
_env('PickCube-Light-v0', max_episode_steps=100, override=True)
class PickCubeLightEnv(PickCubeEnv):
def _setup_lighting(self):
shadow = self.enable_shadow
self._scene.set_ambient_light([0.3, 0.3, 0.3])
self._scene.add_directional_light([1, 1, (- 1)], [1, 1, 1], shadow=shadow, scale=5, shado... |
class TestCommand():
def test_ensure_string_list(self, cmd):
cmd.not_string_list = ['one', 2, 'three']
cmd.yes_string_list = ['one', 'two', 'three']
cmd.not_string_list2 = object()
cmd.yes_string_list2 = 'ok'
cmd.ensure_string_list('yes_string_list')
cmd.ensure_string... |
.parametrize('shape,tile_shape,tile_start', [((2,), (2,), (1,)), ((4,), (2,), (0,)), ((4, 2), (2, 2), (1, 2)), ((2, 4), (2, 2), (2, 1))])
def test_read_write_tiles(tmp_path, shape, tile_shape, tile_start):
a = num.arange(math.prod(shape)).reshape(shape)
write_tiles(ary=a, dirpath=tmp_path, tile_shape=tile_shape... |
class Connection_Combination(nn.Module):
def __init__(self):
super(Connection_Combination, self).__init__()
def forward(self, prev_parallel, prev_above, prev_below, betas):
betas = F.softmax(betas, dim=(- 1))
mix = ((((3 * betas[0]) * prev_parallel) + ((3 * betas[1]) * prev_above)) + ((3... |
class InlineQueryResultCachedDocument(InlineQueryResult):
__slots__ = ('reply_markup', 'caption_entities', 'document_file_id', 'caption', 'title', 'description', 'parse_mode', 'input_message_content')
def __init__(self, id: str, title: str, document_file_id: str, description: Optional[str]=None, caption: Option... |
def init_chain_adapters(*, backend: mcb.Backend, chains: int, initial_point: Mapping[(str, np.ndarray)], step: Union[(CompoundStep, BlockedStep)], model: Model) -> Tuple[(mcb.Run, List[ChainRecordAdapter])]:
(meta, point_fn) = make_runmeta_and_point_fn(initial_point=initial_point, step=step, model=model)
run = ... |
def processor_class_from_name(class_name: str):
for (module_name, processors) in PROCESSOR_MAPPING_NAMES.items():
if (class_name in processors):
module_name = model_type_to_module_name(module_name)
module = importlib.import_module(f'.{module_name}', 'transformers.models')
... |
class DataTrainingArguments():
task_name: Optional[str] = field(default='ncc', metadata={'help': 'The name of the task to train on: ncc'})
dataset_name: Optional[str] = field(default='indic_glue', metadata={'help': 'The name of the dataset to use (via the datasets library).'})
dataset_config_name: Optional[... |
def _coalesce_add_and_mm_nodes(ir_nodes_list: List[IrNode]):
del_node_indices = []
for (i, ir_node) in enumerate(ir_nodes_list):
if ((ir_node.node_type == 'add') and (len(ir_node.inputs) == 1)):
producer_ir_node = ir_nodes_list[(i - 1)]
if ((producer_ir_node.node_type == 'mm') an... |
class Selector(object):
def __init__(self, exps_data, filters=None, custom_filters=None):
self._exps_data = exps_data
if (filters is None):
self._filters = tuple()
else:
self._filters = tuple(filters)
if (custom_filters is None):
self._custom_filte... |
def get_tiny_config_from_class(configuration_class):
if ('OpenAIGPT' in configuration_class.__name__):
return
model_type = configuration_class.model_type
camel_case_model_name = configuration_class.__name__.split('Config')[0]
try:
model_slug = model_type.replace('-', '_')
module ... |
def check_config_attributes():
configs_with_unused_attributes = {}
for config_class in list(CONFIG_MAPPING.values()):
unused_attributes = check_config_attributes_being_used(config_class)
if (len(unused_attributes) > 0):
configs_with_unused_attributes[config_class.__name__] = unused_a... |
def LoadMat(path, project):
if (not Path(path).is_file()):
raise PyUnityException(f'The specified file does not exist: {path}')
with open(path) as f:
contents = f.read().rstrip().splitlines()
if (contents.pop(0) != 'Material'):
raise ProjectParseException('Expected "Material" as line... |
def test_pip(host):
assert host.pip.get_packages()['pip']['version'].startswith('23.')
pkg = host.pip.get_packages(pip_path='/v/bin/pip')['requests']
assert (pkg['version'] == '2.30.0')
outdated = host.pip.get_outdated_packages(pip_path='/v/bin/pip')['requests']
assert (outdated['current'] == pkg['v... |
def get_us_midlatitude_cyclone_abi(base_dir=None, method=None, force=False):
base_dir = (base_dir or config.get('demo_data_dir', '.'))
if (method is None):
method = 'gcsfs'
if (method not in ['gcsfs']):
raise NotImplementedError("Demo data download method '{}' not implemented yet.".format(me... |
def main() -> None:
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler(sys.stdout))
parser = argparse.ArgumentParser(description='OS distro info tool')
parser.add_argument('--json', '-j', help='Output in machine readable format', action='store... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, plan... |
def build_field_transform_default_imagenet(config: Optional[List[Dict[(str, Any)]]], default_transform: Optional[Callable]=None, split: Optional[bool]=None, key: Union[(int, str)]='input', key_map_transform: Optional[Callable]=DEFAULT_KEY_MAP) -> Callable:
assert ((default_transform is None) or (split is None)), 'C... |
def map_reduce(iterable, keyfunc, valuefunc=None, reducefunc=None):
valuefunc = ((lambda x: x) if (valuefunc is None) else valuefunc)
ret = defaultdict(list)
for item in iterable:
key = keyfunc(item)
value = valuefunc(item)
ret[key].append(value)
if (reducefunc is not None):
... |
def _get_vendored_config():
config_fp = os.environ.get('QIIME2_CONFIG')
if (config_fp is None):
if os.path.exists((fp_ := os.path.join(appdirs.user_config_dir('qiime2'), 'qiime2_config.toml'))):
config_fp = fp_
elif os.path.exists((fp_ := os.path.join(appdirs.site_config_dir('qiime2'... |
class Seq2SeqTSModelOutput(ModelOutput):
last_hidden_state: torch.FloatTensor = None
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
cross_attentions: Opti... |
def _set_filepicker_kwargs(fileDlg, **kwargs):
NO_MATCH = object()
for (kk, vv) in kwargs.items():
formattedName = (kk[0].upper() + kk[1:])
if (formattedName == 'Options'):
enumCls = fileDlg.Option
else:
enumCls = getattr(fileDlg, formattedName, NO_MATCH)
... |
class TimeSolveLossActiveMaterial(SolveModel):
param_names = ['model', 'model option', 'solver class']
params = ([pybamm.lithium_ion.SPM, pybamm.lithium_ion.DFN], ['none', 'stress-driven', 'reaction-driven', 'stress and reaction-driven'], [pybamm.CasadiSolver, pybamm.IDAKLUSolver])
def setup(self, model, pa... |
class EngineConfiguration(object):
def new() -> 'EngineConfiguration':
raise NotImplementedError
def from_file(filepath: Path) -> 'EngineConfiguration':
raise NotImplementedError
def from_str(s: str) -> 'EngineConfiguration':
raise NotImplementedError
def to_str(self) -> str:
... |
def hybrid_training(threshold, use_threshold, stage_nums, core_nums, train_step_nums, batch_size_nums, learning_rate_nums, keep_ratio_nums, train_data_x, train_data_y, test_data_x, test_data_y):
stage_length = len(stage_nums)
col_num = stage_nums[1]
tmp_inputs = [[[] for i in range(col_num)] for i in range(... |
def build_sdist(sdist_directory, config_settings):
target = 'pkg2-0.5.tar.gz'
with tarfile.open(pjoin(sdist_directory, target), 'w:gz', format=tarfile.PAX_FORMAT) as tf:
def _add(relpath):
tf.add(relpath, arcname=('pkg2-0.5/' + relpath))
_add('pyproject.toml')
for pyfile in g... |
class BaseCascade(BaseMulti):
def prepare(cls, obj, solver):
if (not getattr(obj, 'Cascade', True)):
return super(BaseCascade, cls).prepare(obj, solver)
func = cls.constraintFunc(obj, solver)
if (not func):
return
props = cls.getPropertyValues(obj)
pre... |
def resolve(request):
preimage = None
if ('secrethash' not in request):
return preimage
x_secret = '0x2ff886d47b156de00d4cad5d8cb5b572adfe35e6d2f65ee'
x_secret_hash = to_hex(sha256(to_bytes(hexstr=x_secret)).digest())
if (request['secrethash'] == x_secret_hash):
preimage = {'secret':... |
def sicpovm_preparation_matrix(label: str) -> np.array:
res = np.array([])
if (label == 'S0'):
res = np.array([[1, 0], [0, 0]], dtype=complex)
if (label == 'S1'):
res = (np.array([[1, np.sqrt(2)], [np.sqrt(2), 2]], dtype=complex) / 3)
if (label == 'S2'):
res = (np.array([[1, (np.... |
def test_temporary_directory_python_3_10_or_newer(mocker: MockerFixture) -> None:
mocked_rmtree = mocker.patch('shutil.rmtree')
mocked_temp_dir = mocker.patch('tempfile.TemporaryDirectory')
mocked_mkdtemp = mocker.patch('tempfile.mkdtemp')
mocker.patch.object(sys, 'version_info', (3, 10))
with tempo... |
def to_pickle(data):
def process_item(item):
dtype = type(item)
if (dtype in (str, int, float, bool, bytes, SafeString, SafeBytes)):
return item
elif (dtype == tuple):
return tuple((process_item(val) for val in item))
elif (dtype in (list, _SaverList)):
... |
def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, config_file, pytorch_dump_path):
config = T5Config.from_json_file(config_file)
print('Building PyTorch model from configuration: {}'.format(str(config)))
model = T5Model(config)
load_tf_weights_in_t5(model, config, tf_checkpoint_path)
print('S... |
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 get_args():
parser = argparse.ArgumentParser(description="This script copies the 'srcdir'\n data directory to output data directory 'dir'\n while modifying the utterances so that there are\n 3 copies of each ut... |
def get_layer_path_for_storage(storage_uuid, cas_path, content_checksum):
store = config.store
if (not cas_path):
logger.debug('Serving layer from legacy v1 path for storage %s', storage_uuid)
return store.v1_image_layer_path(storage_uuid)
return store.blob_path(content_checksum) |
class Predictor(cog.Predictor):
def setup(self):
faceenhancer_model = {'name': 'GPEN-BFR-256', 'size': 256, 'channel_multiplier': 1, 'narrow': 0.5}
self.faceenhancer = FaceEnhancement(size=faceenhancer_model['size'], model=faceenhancer_model['name'], channel_multiplier=faceenhancer_model['channel_mu... |
def run_test(case, m):
m.elaborate()
VStructuralTranslatorL2.is_verilog_reserved = (lambda s, x: (x in verilog_reserved))
tr = VStructuralTranslatorL2(m)
tr.clear(m)
tr._rtlir_tr_unpacked_q = deque()
tr.translate_structural(m)
ports = tr.structural.decl_ports[m]
wires = tr.structural.dec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.