code stringlengths 281 23.7M |
|---|
class FakeFCI(pyscf.fci.direct_spin1_symm.FCI):
def __init__(self, mol, nelec=None):
self.nelec = nelec
self.fake_potential = None
super().__init__(mol)
def kernel(self, h1, h2, norb, nelec, *args, **kwargs):
if (self.nelec is not None):
nelec = self.nelec
if ... |
def evaluate(prefix='./', mode='dev', evaluate_dir=None, evaluate_prefix=None, output_file=None, output_dir=None, python_evaluate=False, triplet=False):
sclite_path = './software/sclite'
print(os.getcwd())
os.system(f'bash {evaluate_dir}/preprocess.sh {(prefix + output_file)} {prefix}tmp.ctm {prefix}tmp2.ct... |
def concat_2d(ds: Dataset, dims: Tuple[(Hashable, Hashable)]) -> DataArray:
arrs = []
for var in ds:
arr = ds[var]
if (arr.dims[0] != dims[0]):
continue
if (arr.ndim > 2):
raise ValueError(f'All variables must have <= 2 dimensions (variable {var} has shape {arr.sh... |
def find_byte_range_of_section(path, start_string):
with open(path) as f:
start = None
end = None
l = 0
for line in f:
if (start and (line.strip() == '') and ((l - start) > 100)):
end = l
break
if ((start_string in line) and (no... |
class INPDiff(object):
def __init__(self, model1=None, model2=None):
m1 = model1
m2 = model2
if isinstance(m1, str):
m1 = swmmio.Model(m1)
if isinstance(m2, str):
m2 = swmmio.Model(m2)
self.m1 = m1
self.m2 = m2
self.diffs = OrderedDict(... |
class PlayChunkData(Packet):
id = 32
to = 1
def __init__(self, chunk: Chunk, full: bool) -> None:
super().__init__()
self.chunk = chunk
self.full = full
def encode(self) -> bytes:
out = ((Buffer.pack('i', self.chunk.x) + Buffer.pack('i', self.chunk.z)) + Buffer.pack('?', ... |
class TestConstraintPropagation(unittest.TestCase):
def test_3by3_matrix(self):
affinity = np.array([[1, 0.25, 0], [0.31, 1, 0], [0, 0, 1]])
constraint_matrix = np.array([[1, 1, 0], [1, 1, 0], [0, 0, 0]])
adjusted_affinity = constraint.ConstraintPropagation(alpha=0.6).adjust_affinity(affinit... |
class ExpressionStmt(Statement):
__slots__ = ('expr',)
__match_args__ = ('expr',)
expr: Expression
def __init__(self, expr: Expression) -> None:
super().__init__()
self.expr = expr
def accept(self, visitor: StatementVisitor[T]) -> T:
return visitor.visit_expression_stmt(self) |
class CheckFnSignatureTests(unittest.TestCase):
def test_no_args(self):
def foo():
pass
with self.assertRaises(ValueError):
server._fn_accepts_additional_args(foo, [])
def test_var_args(self):
def foo(*args):
pass
server._fn_accepts_additional_... |
def test_opts():
paramSpec = [dict(name='bool', type='bool', readonly=True), dict(name='color', type='color', readonly=True)]
param = pt.Parameter.create(name='params', type='group', children=paramSpec)
tree = pt.ParameterTree()
tree.setParameters(param)
assert (_getWidget(param.param('bool')).isEna... |
_task('hubert_pretraining', dataclass=HubertPretrainingConfig)
class HubertPretrainingTask(FairseqTask):
cfg: HubertPretrainingConfig
def __init__(self, cfg: HubertPretrainingConfig, dictionaries: Dict[(str, Dictionary)]) -> None:
super().__init__(cfg)
logger.info(f'current directory is {os.getc... |
def test_swift_session_class():
swift_session = SwiftSession(swift_storage_url='foo', swift_auth_token='bar')
assert swift_session._creds
assert (swift_session.get_credential_options()['SWIFT_STORAGE_URL'] == 'foo')
assert (swift_session.get_credential_options()['SWIFT_AUTH_TOKEN'] == 'bar') |
class LatentEditor(object):
def __init__(self, stylegan_generator):
self.generator = stylegan_generator
self.interfacegan_directions = {'age': torch.load('editing/interfacegan_directions/age.pt').cuda(), 'smile': torch.load('editing/interfacegan_directions/smile.pt').cuda(), 'pose': torch.load('edit... |
.parametrize('username,password', users)
.parametrize('project_id', projects)
def test_project_update_tasks_get(db, client, username, password, project_id):
client.login(username=username, password=password)
url = reverse('project_update_tasks', args=[project_id])
response = client.get(url)
if (project_... |
class ImageNetTrain(ImageNetBase):
NAME = 'ILSVRC2012_train'
URL = '
AT_HASH = 'a306397ccf9c2eadc254227c0fd938e2'
FILES = ['ILSVRC2012_img_train.tar']
SIZES = []
def __init__(self, process_images=True, data_root=None, **kwargs):
self.process_images = process_images
self.data_root... |
def decode_subframe(inp, blocksize, sampledepth):
inp.read_uint(1)
subframe_type = inp.read_uint(6)
shift = inp.read_uint(1)
if (shift == 1):
while (inp.read_uint(1) == 0):
shift += 1
sampledepth -= shift
if (subframe_type == 0):
result = ([inp.read_signed_int(sampled... |
class WithInternationalPricingPipelineEngine(zf.WithFXRates, WithInternationalDailyBarData):
def init_class_fixtures(cls):
super(WithInternationalPricingPipelineEngine, cls).init_class_fixtures()
adjustments = NullAdjustmentReader()
cls.loaders = {GB_EQUITIES: EquityPricingLoader(cls.daily_b... |
def get_class_by_name(problem_name, model_name):
if (problem_name == 'conditioned_separation'):
if (model_name == 'CUNET_TFC_FiLM'):
return DCUN_TFC_FiLM_Framework
elif (model_name == 'CUNET_TFC_FiLM_TDF'):
return DCUN_TFC_FiLM_TDF_Framework
elif (model_name == 'CUNET... |
def test_ioc_file(runner, mocker):
mocked_func = mocker.patch('products.vmware_cb_response.CbResponse._authenticate')
mocked_nested_process_search = mocker.patch('products.vmware_cb_response.CbResponse.nested_process_search')
with runner.isolated_filesystem() as temp_dir:
ioc_file_path = os.path.joi... |
def test_executor_should_append_subdirectory_for_git(mocker: MockerFixture, tmp_venv: VirtualEnv, pool: RepositoryPool, config: Config, artifact_cache: ArtifactCache, io: BufferedIO, mock_file_downloads: None, wheel: Path) -> None:
package = Package('demo', '0.1.2', source_type='git', source_reference='master', sou... |
def _get_command_doc_count(cmd, parser):
for param in inspect.signature(cmd.handler).parameters.values():
if (cmd.get_arg_info(param).value in cmd.COUNT_COMMAND_VALUES):
(yield '')
(yield '==== count')
try:
(yield parser.arg_descs[param.name])
... |
def correct_order(node_id, sampled_nodes, train_labels, multi, nlabel):
(matched_labels, matched_index) = ([], [])
for (index, each) in enumerate(node_id):
if (each in sampled_nodes):
if multi:
curr_label = np.zeros(nlabel).astype(int)
curr_label[train_labels[... |
def get_member_flags(name: str, itype: Instance, class_obj: bool=False) -> set[int]:
info = itype.type
method = info.get_method(name)
setattr_meth = info.get_method('__setattr__')
if method:
if isinstance(method, Decorator):
if (method.var.is_staticmethod or method.var.is_classmethod... |
class Settings():
_settings_file = 'settings.pickle'
def __init__(self):
self.book = BookSettings()
self.database = DatabaseSettings()
self.moveSelection = MoveSelectionSettings()
self.engine = EngineSettings()
self.load_from_file()
def save_to_file(self):
wit... |
def _make_send_recv_callbacks(socket: WebSocketConnection) -> tuple[(SendCoroutine, RecvCoroutine)]:
async def sock_send(value: Any) -> None:
(await socket.send(json.dumps(value)))
async def sock_recv() -> Any:
data = (await socket.recv())
if (data is None):
raise Stop()
... |
class DenseWTUnet(nn.Module):
def __init__(self, growth_rate=32, block_config=(6, 12), num_init_features=4, bn_size=4, drop_rate=0):
super(DenseWTUnet, self).__init__()
self.DWT = common.DWT()
self.IWT = common.IWT()
self.features = nn.Sequential(OrderedDict([('conv0', nn.Conv2d(4, n... |
def test_prepare_uv_t_counts():
num_bits_p = 6
eta = 10
num_atoms = 10
lambda_zeta = 10
num_bits_nuc_pos = 8
m_param = (2 ** ((2 * num_bits_p) + 3))
num_bits_m = (m_param - 1).bit_length()
expected_cost = ((((3 * (num_bits_p ** 2)) + num_bits_p) + ((4 * num_bits_m) * (num_bits_p + 1))) +... |
class Install():
def __init__(self, environment):
self.output = environment.output
self.env = environment
if ((not self.env.is_installer) and (not self.env.updater)):
self.ask_continue()
self.check_missing_dep()
self.check_conda_missing_dep()
if (self.env.... |
class RtePVP(PVP):
VERBALIZER = {'not_entailment': ['No'], 'entailment': ['Yes']}
def get_parts(self, example: InputExample) -> FilledPattern:
text_a = self.shortenable(example.text_a)
text_b = self.shortenable(example.text_b.rstrip(string.punctuation))
if (self.pattern_id == 1):
... |
def build_lr_scheduler(optimizer, lr, lr_clip, lr_decay_list, lr_decay_rate, last_epoch):
def lr_lbmd(cur_epoch):
cur_decay = 1
for decay_step in lr_decay_list:
if (cur_epoch >= decay_step):
cur_decay = (cur_decay * lr_decay_rate)
return max(cur_decay, (lr_clip / ... |
('/api/file_system/move', methods=['POST'])
def move_files() -> Response:
request_json = request.get_json()
(user_id, chat_id) = get_user_and_chat_id_from_request_json(request_json)
root_path = create_personal_folder(user_id)
nodes = request_json['nodes']
try:
if (os.path.exists(root_path) a... |
class DtypeTestCase(ZiplineTestCase):
def correct_dtype(cls, dtypes):
_space(dtype_=dtypes)
def test(self, dtype_):
class Correct(cls):
missing_value = missing_values.get(dtype_, NotSpecified)
inputs = []
window_length = 1
d... |
def test_select_handle_free_center(view, item):
view.scene.addItem(item)
view.scale(0.5, 0.5)
item.SELECT_FREE_CENTER = 10
with patch.object(item, 'bounding_rect_unselected', return_value=QtCore.QRectF(0, 0, 100, 80)):
assert (item.select_handle_free_center() == QtCore.QRectF(40, 30, 20, 20)) |
def test_03_callbacks(driver):
with get_eel_server('examples/03 - sync_callbacks/sync_callbacks.py', 'sync_callbacks.html') as eel_url:
driver.get(eel_url)
assert (driver.title == 'Synchronous callbacks')
console_logs = get_console_logs(driver, minimum_logs=1)
assert ('Got this from ... |
class ChannelAttention(nn.Module):
def __init__(self, channels):
super().__init__()
self.global_avgpool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Conv2d(channels, channels, 1, 1, 0, bias=True)
self.act = nn.Hardsigmoid(inplace=True)
def forward(self, x: torch.Tensor) -> torch.Tensor... |
class ArchiveCheck(_Archive):
def open(self, relpath):
abspath = os.path.join(str(self.path), relpath)
return open(abspath, 'r')
def relative_iterdir(self, relpath='.'):
for p in pathlib.Path(self.path).iterdir():
(yield str(p.relative_to(self.path)))
def _get_uuid(self):... |
def search_point_group_ops(cell, tol=SYMPREC):
a = cell.lattice_vectors()
G = np.dot(a, a.T)
pbc_axis = np.array([1, 1, 1], dtype=bool)
if (cell.dimension < 3):
pbc_axis[cell.dimension:] = False
a_norm = np.sqrt(np.diag(G))
a_angle = np.arccos((G / np.outer(a_norm, a_norm)))
tol2 = (... |
def get_auth_headers(repository=None, scopes=None):
headers = {}
realm_auth_path = url_for('v2.generate_registry_jwt')
authenticate = 'Bearer realm="{0}{1}",service="{2}"'.format(get_app_url(), realm_auth_path, app.config['SERVER_HOSTNAME'])
if repository:
scopes_string = 'repository:{0}'.format... |
class OurMultiheadAttention(nn.Module):
def __init__(self, feat_dim, n_head, d_k=None, d_v=None):
super(OurMultiheadAttention, self).__init__()
if (d_k is None):
d_k = (feat_dim // n_head)
if (d_v is None):
d_v = (feat_dim // n_head)
self.n_head = n_head
... |
def execute_policy_on_repo(policy, repo_id, namespace_id, tag_page_limit=100):
policy_to_func_map = {AutoPruneMethod.NUMBER_OF_TAGS.value: prune_repo_by_number_of_tags, AutoPruneMethod.CREATION_DATE.value: prune_repo_by_creation_date}
if (policy_to_func_map.get(policy.method, None) is None):
raise Inval... |
class Effect4321(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'ECM')), 'scanLadarStrengthBonus', src.getModifiedItemAttr('subsystemBonusCaldariCore2'), skill='Caldari Core Systems', **kwargs)
... |
def test_verify_docs_python_org(benchmark, pytestconfig):
limbo_root = pytestconfig.getoption('--x509-limbo-root', skip=True)
with open(os.path.join(limbo_root, 'limbo.json'), 'rb') as f:
[testcase] = [tc for tc in json.load(f)['testcases'] if (tc['id'] == 'online::docs.python.org')]
with open(certi... |
class QuantDtypeBwInfo():
def __init__(self, act_dtype: QuantizationDataType, act_bw: int, param_dtype: QuantizationDataType=QuantizationDataType.undefined, param_bw: int=0):
self.act_dtype = act_dtype
self.act_bw = act_bw
self.param_dtype = param_dtype
self.param_bw = param_bw
... |
def test_marker_union_intersect_single_marker() -> None:
m = parse_marker('sys_platform == "darwin" or python_version < "3.4"')
intersection = m.intersect(parse_marker('implementation_name == "cpython"'))
assert (str(intersection) == 'sys_platform == "darwin" and implementation_name == "cpython" or python_v... |
.skip(reason='SRML server is undergoing maintenance as of 12-2023')
_on_pvlib_version('0.11')
.remote_data
.flaky(reruns=RERUNS, reruns_delay=RERUNS_DELAY)
def test_15_minute_dt_index():
with pytest.warns(pvlibDeprecationWarning, match='get_srml instead'):
data = srml.read_srml_month_from_solardat('TW', 201... |
class ExtendedRequestSupport():
def _process_exception(resp, **kwargs):
if ('slave' not in kwargs):
err = {'message': 'Broadcast message, ignoring errors!!!'}
elif isinstance(resp, ExceptionResponse):
err = {'original_function_code': f'{resp.original_code} ({hex(resp.original... |
def test_layer_control_initialization():
layer_control = LayerControl()
assert (layer_control._name == 'LayerControl')
assert (layer_control.options['position'] == 'topright')
assert (layer_control.options['collapsed'] is True)
assert (layer_control.options['autoZIndex'] is True)
assert (layer_c... |
class Venv():
def __init__(self, path: Path, *, verbose: bool=False, python: str=DEFAULT_PYTHON) -> None:
self.root = path
self.python = python
(self.bin_path, self.python_path, self.man_path) = get_venv_paths(self.root)
self.pipx_metadata = PipxMetadata(venv_dir=path)
self.v... |
_torch
class AutoModelTest(unittest.TestCase):
def test_model_from_pretrained(self):
for model_name in BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
config = AutoConfig.from_pretrained(model_name)
self.assertIsNotNone(config)
self.assertIsInstance(config, BertConfig)
... |
class ASPP(nn.Module):
def __init__(self, backbone, output_stride, BatchNorm):
super(ASPP, self).__init__()
if (backbone == 'drn'):
inplanes = 512
elif (backbone == 'mobilenet'):
inplanes = 320
else:
inplanes = 2048
if (output_stride == 16)... |
def _find_caller():
frame = sys._getframe(2)
while frame:
code = frame.f_code
if (os.path.join('utils', 'logger.') not in code.co_filename):
mod_name = frame.f_globals['__name__']
if (mod_name == '__main__'):
mod_name = 'detectron2'
return (mod... |
def init(disp, info):
disp.extension_add_method('display', 'xinput_query_version', query_version)
disp.extension_add_method('window', 'xinput_select_events', select_events)
disp.extension_add_method('display', 'xinput_query_device', query_device)
disp.extension_add_method('window', 'xinput_grab_device',... |
def test_dsl_async_cmd_dict_run_must_exist():
with pytest.raises(ContextError) as err:
AsyncCmdStep('blah', Context({'cmds': {'runs': 'abc'}}))
assert (str(err.value) == "cmds.run doesn't exist for blah.\nThe input should look like this in expanded syntax:\ncmds:\n run:\n - ./my-executable --arg\n ... |
def create_gunicorn_worker():
engines = set([config[0] for config in list(app.config.get('DISTRIBUTED_STORAGE_CONFIG', {}).values())])
feature_flag = ('SwiftStorage' in engines)
worker = GunicornWorker(__name__, app, ChunkCleanupWorker(chunk_cleanup_queue, poll_period_seconds=POLL_PERIOD_SECONDS), feature_f... |
class VHeuristic():
def __init__(self):
self.staticParts = []
self.randomPart = None
self.minPart = None
self.maxPart = None
def random(self, variables=None):
variables = flatten(variables)
checkType(variables, ([Variable], type(None)))
self.randomPart = (... |
class _TfDataCheckpointer():
def __init__(self, dataset_iterator: tf.data.Iterator):
self._dataset_ckpt = tf.train.Checkpoint(ds=dataset_iterator)
def save(self, filename: str):
self._dataset_ckpt.write(filename)
def load(self, filename: str):
self._dataset_ckpt.read(filename).assert... |
def setup_virtual_environments(distributions: dict[(str, PackageDependencies)], args: TestConfig, tempdir: Path) -> None:
if (not distributions):
return
no_external_dependencies_venv = VenvInfo(pip_exe='', python_exe=sys.executable)
external_requirements_to_distributions: defaultdict[(frozenset[str]... |
def liouvillian_ref(H, c_ops=()):
L = (((- 1j) * (qutip.spre(H) - qutip.spost(H))) if H else 0)
for c in c_ops:
if c.issuper:
L += c
else:
cdc = (c.dag() * c)
L += qutip.sprepost(c, c.dag())
L -= (0.5 * (qutip.spre(cdc) + qutip.spost(cdc)))
ret... |
def generate_auto_eval_text(e1, e2, print_text=True):
answer_1 = e1['response']
answer_2 = e2['response']
instruction = e1['prompt']
instruction2 = e2['prompt']
assert (instruction == instruction2)
eval_prompt = 'We would like to request your feedback on the performance of two AI assistants in r... |
def test_activate_activates_non_existing_virtualenv_no_envs_file(mocker: MockerFixture, tester: CommandTester, venv_cache: Path, venv_name: str, venvs_in_cache_config: None) -> None:
mocker.patch('shutil.which', side_effect=(lambda py: f'/usr/bin/{py}'))
mocker.patch('subprocess.check_output', side_effect=check... |
def upgrade_config(cfg: CN, to_version: Optional[int]=None) -> CN:
cfg = cfg.clone()
if (to_version is None):
to_version = _C.VERSION
assert (cfg.VERSION <= to_version), 'Cannot upgrade from v{} to v{}!'.format(cfg.VERSION, to_version)
for k in range(cfg.VERSION, to_version):
converter =... |
class TestInputInvoiceMessageContentBase():
title = 'invoice title'
description = 'invoice description'
payload = 'invoice payload'
provider_token = 'provider token'
currency = 'PTBCoin'
prices = [LabeledPrice('label1', 42), LabeledPrice('label2', 314)]
max_tip_amount = 420
suggested_tip... |
class AMPClientFactory(protocol.ReconnectingClientFactory):
initialDelay = 1
factor = 1.5
maxDelay = 1
noisy = False
def __init__(self, server):
self.server = server
self.protocol = AMPServerClientProtocol
self.maxDelay = 10
self.broadcasts = []
def startedConnect... |
.requires_cython
def test_CoeffReuse():
coeff1 = coefficient('cos(w * t * pi)', args={'w': 3.0})
coeff2 = coefficient('cos(w2*t * pi)', args={'w2': 1.2})
coeff3 = coefficient('cos( my_var * t*pi)', args={'my_var': (- 1.2)})
assert isinstance(coeff2, coeff1.__class__)
assert isinstance(coeff3, coeff... |
class TestJob(TestCase):
def test_create_job(self):
job = Job(random_job, 'hi', arg2='there')
self.assertIsInstance(job, Job)
def test_create_job_from_message(self):
message = Message(body=dumps({'callable': random_job, 'args': (), 'kwargs': {}}))
job = Job.from_message(message)
... |
def _ebcdic_to_ascii(s):
global _ebcdic_to_ascii_map
if (not _ebcdic_to_ascii_map):
emap = (0, 1, 2, 3, 156, 9, 134, 127, 151, 141, 142, 11, 12, 13, 14, 15, 16, 17, 18, 19, 157, 133, 8, 135, 24, 25, 146, 143, 28, 29, 30, 31, 128, 129, 130, 131, 132, 10, 23, 27, 136, 137, 138, 139, 140, 5, 6, 7, 144, 145... |
def run_one_process(rank, world_size, args, cfg):
import numpy as np
np.set_printoptions(3)
set_random_seed((args.seed + rank))
if (is_not_null(cfg.env_cfg) and (len(args.gpu_ids) > 0)):
if (args.sim_gpu_ids is not None):
assert (len(args.sim_gpu_ids) == len(args.gpu_ids)), 'Number o... |
class QueueCommandManager(CommandManager):
def __init__(self):
super(QueueCommandManager, self).__init__()
self.queue = Queue()
self.sent = []
def enqueue(self, fn):
self.queue.put(fn)
def user_wait(self, duration):
self.enqueue((lambda t: sleep((duration + int(PY3)))... |
def grok_station_xml(data, tmin, tmax):
stations = {}
for (sta, sta_epo, cha, cha_epo) in xmlzip(data, ('Station', 'StationEpoch', 'Channel', 'Epoch')):
(sta_beg, sta_end, cha_beg, cha_end) = [tdatetime(x) for x in (sta_epo.StartDate, sta_epo.EndDate, cha_epo.StartDate, cha_epo.EndDate)]
if (not... |
class _RandomSplitterIterDataPipe(IterDataPipe):
def __init__(self, source_datapipe: IterDataPipe, total_length: int, weights: Dict[(T, Union[(int, float)])], seed):
self.source_datapipe: IterDataPipe = source_datapipe
self.total_length: int = total_length
self.remaining_length: int = total_... |
class Migration(migrations.Migration):
dependencies = [('contenttypes', '0002_remove_content_type_name'), ('sponsors', '0029_auto__2015')]
operations = [migrations.CreateModel(name='BenefitFeature', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'))], optio... |
class AmountDialog(Factory.Popup):
show_max = BooleanProperty(False)
app = App.get_running_app()
def __init__(self, show_max, amount, cb):
Factory.Popup.__init__(self)
self.show_max = show_max
self.callback = cb
if amount:
self.ids.kb.amount = amount
def updat... |
class FactorizedInteraction(nn.Module):
def __init__(self, input_dim, output_dim, bias=True, residual_type='sum'):
super(FactorizedInteraction, self).__init__()
self.residual_type = residual_type
if (residual_type == 'sum'):
output_dim = (output_dim * 2)
else:
... |
class RateDistortionLoss(nn.Module):
def __init__(self, lmbda=0.01, metrics='mse'):
super().__init__()
self.mse = nn.MSELoss()
self.lmbda = lmbda
self.metrics = metrics
def forward(self, output, target):
(N, _, H, W) = target.size()
out = {}
num_pixels = (... |
class Effect6733(BaseEffect):
type = ('active', 'gang')
def handler(fit, module, context, projectionRange, **kwargs):
for x in range(1, 5):
if module.getModifiedChargeAttr('warfareBuff{}ID'.format(x)):
value = module.getModifiedItemAttr('warfareBuff{}Value'.format(x))
... |
class ModelArguments():
model_name_or_path: Optional[str] = field(default=None, metadata={'help': "The model checkpoint for weights initialization.Don't set if you want to train a model from scratch."})
model_type: Optional[str] = field(default=None, metadata={'help': ('If training from scratch, pass a model ty... |
class Effect8362(BaseEffect):
runTime = 'early'
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Warp Disrupt Field Generator')), 'signatureRadiusBonus', ship.getModifiedItemAttr('eliteBonusHeavyInterdict... |
class FeesEstimateRequest(MWSDataType):
def __init__(self, marketplace_id: MarketplaceEnumOrStr, id_type: str, id_value: str, price_to_estimate_fees: PriceToEstimateFees, is_amazon_fulfilled: bool, identifier: str):
self.marketplace_id = marketplace_id
self.id_type = id_type
self.id_value = ... |
def get_model(args, DATASET_CONFIG):
if args.use_height:
num_input_channel = ((int(args.use_color) * 3) + 1)
else:
num_input_channel = (int(args.use_color) * 3)
model = GroupFreeDetector_DA(num_class=DATASET_CONFIG.num_class, num_heading_bin=DATASET_CONFIG.num_heading_bin, num_size_cluster=D... |
class SummaryTracker(object):
def __init__(self, ignore_self=True):
self.s0 = summary.summarize(muppy.get_objects())
self.summaries = {}
self.ignore_self = ignore_self
def create_summary(self):
if (not self.ignore_self):
res = summary.summarize(muppy.get_objects())
... |
def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
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_args,... |
def drop_path(x, drop_prob: float=0.0, training: bool=False):
if ((drop_prob == 0.0) or (not training)):
return x
keep_prob = (1 - drop_prob)
shape = ((x.shape[0],) + ((1,) * (x.ndim - 1)))
random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
if (keep_prob > 0.0):
random_tensor.d... |
def backup_output(output: Path) -> None:
backup_dir = os.environ.get('TMP_OUTPUT_PATH')
snapshot_dir = os.environ.get('SNAPSHOT_PATH')
if (backup_dir is None):
assert (snapshot_dir is None)
return
assert (snapshot_dir is not None)
try:
relative_output_dir = output.relative_to... |
()
def pycache_clean(context):
with context.cd(TASK_ROOT_STR):
dirs = set()
for (root, dirnames, _) in os.walk(os.curdir):
if ('__pycache__' in dirnames):
dirs.add(os.path.join(root, '__pycache__'))
print('Removing __pycache__ directories')
rmrf(dirs, verb... |
class PreOCIModel(SuperuserDataInterface):
def get_repository_build(self, uuid):
try:
build = model.build.get_repository_build(uuid)
except model.InvalidRepositoryBuildException as e:
raise InvalidRepositoryBuildException(str(e))
repo_namespace = build.repository.name... |
def parse_gstreamer_taglist(tags):
merged = {}
for key in tags.keys():
value = tags[key]
if (key == 'extended-comment'):
if (not isinstance(value, list)):
value = [value]
for val in value:
if (not isinstance(val, str)):
... |
class GdbLaunch(sublime_plugin.WindowCommand):
def run(self):
global exec_settings
s = self.window.active_view().settings()
exec_choices = s.get('sublimegdb_executables')
if ((exec_choices is None) or (type(exec_choices) != dict)):
global gdb_threads
exec_sett... |
class HDDGraph(_Graph):
fixed_upper_bound = True
orientations = base.ORIENTATION_HORIZONTAL
defaults = [('path', '/', 'Partition mount point.'), ('space_type', 'used', 'free/used')]
def __init__(self, **config):
_Graph.__init__(self, **config)
self.add_defaults(HDDGraph.defaults)
... |
def test_deprecated_alias_method(recwarn_always):
obj = Alias()
assert (obj.old_hotness_method() == 'new hotness method')
got = recwarn_always.pop(TrioAsyncioDeprecationWarning)
msg = got.message.args[0]
assert ('test_deprecate.Alias.old_hotness_method is deprecated' in msg)
assert ('test_deprec... |
class LazyEncodingPats(object):
def __call__(self, binary=False):
attr = ('binary_pats' if binary else 'unicode_pats')
pats = getattr(self, attr, None)
if (pats is None):
pats = tuple(compile_pats(binary))
setattr(self, attr, pats)
for pat in pats:
... |
def report_long_words(st, locn, toks):
word = toks[0]
if (len(word) > 3):
print(f'Found {word!r} on line {pp.lineno(locn, st)} at column {pp.col(locn, st)}')
print('The full line of text was:')
print(f'{pp.line(locn, st)!r}')
print(f" {'^':>{pp.col(locn, st)}}")
print() |
class DecoderOptions(BaseOptions):
def initialize(self):
BaseOptions.initialize(self)
self.parser.add_argument('--display_single_pane_ncols', type=int, default=0, help='if positive, display all images in a single visdom web panel with certain number of images per row.')
self.parser.add_argum... |
class MemoryDockerCollector(MemoryCgroupCollector):
def collect(self):
if (docker is None):
self.log.error('Unable to import docker')
return
self.containers = dict(((c['Id'], c['Names'][0][1:]) for c in docker.Client().containers(all=True) if (c['Names'] is not None)))
... |
def test_message_ack_timing_keeper_edge_cases():
matk = MessageAckTimingKeeper()
assert (matk.generate_report() == [])
processed = Processed(MessageID(999), make_signature())
matk.finalize_message(processed)
assert (matk.generate_report() == [])
reveal_secret = RevealSecret(MessageID(1), make_si... |
def parse_json_file(filepath, metric):
filepath = Path(filepath)
name = filepath.name.split('.')[0]
with filepath.open('r') as f:
try:
data = json.load(f)
except json.decoder.JSONDecodeError as err:
print(f'Error reading file "{filepath}"')
raise err
i... |
def cdf_generator(N=(10 ** 6)):
assert (type(N) == int), 'N should be an int.'
pi = np.pi
Theta_dist = np.empty(N)
for i in range(N):
psi = (random() * pi)
phi = ((random() * 2) * pi)
costh = random()
cosiota = random()
Fplus = ((((0.5 * (1 + (costh ** 2))) * np.c... |
_vcs_handler('git', 'pieces_from_vcs')
def git_pieces_from_vcs(tag_prefix: str, root: str, verbose: bool, runner: Callable=run_command) -> Dict[(str, Any)]:
GITS = ['git']
if (sys.platform == 'win32'):
GITS = ['git.cmd', 'git.exe']
env = os.environ.copy()
env.pop('GIT_DIR', None)
runner = fu... |
def test(args):
logger = logging.getLogger(__name__)
DATA_PATH = hydra.utils.to_absolute_path(args.dataset_dir)
if (args.dataset == 'ModelNet40'):
test_loader = DataLoader(ModelNet40(DATA_PATH, partition='test', num_points=args.num_points), num_workers=8, batch_size=args.test_batch_size, shuffle=Fal... |
class TestMessageBase():
id_ = 1
from_user = User(2, 'testuser', False)
date = datetime.utcnow()
chat = Chat(3, 'private')
test_entities = [{'length': 4, 'offset': 10, 'type': 'bold'}, {'length': 3, 'offset': 16, 'type': 'italic'}, {'length': 3, 'offset': 20, 'type': 'italic'}, {'length': 4, 'offset... |
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
cfg.merge_from_dict(default_cfg)
if (args.options is not None):
cfg.merge_from_dict(args.options)
if cfg.get('cudnn_benchmark', False):
torch.backends.cudnn.benchmark = True
cfg.gpus = args.gpus
if (args.work_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.