code stringlengths 281 23.7M |
|---|
class MichaudTauFatigue(TauFatigue):
def dynamics_suffix() -> str:
return 'ma'
def fatigue_suffix() -> str:
return 'mf'
def __init__(self, minus: MichaudFatigue, plus: MichaudFatigue, state_only: bool=False, apply_to_joint_dynamics: bool=False, **kwargs):
super(MichaudTauFatigue, sel... |
class BbxBlur(object):
def __init__(self, compress_ratio):
self.compress_ratio = compress_ratio
def __call__(self, img, bbx):
(original_width, original_height) = (img.width, img.height)
(compressed_width, compressed_height) = (int((original_width / math.sqrt(self.compress_ratio))), int((... |
def parsed_sql_has_superlative(sql_query_parsed_from_spider, schema):
if ((sql_query_parsed_from_spider.get('limit') == 1) and sql_query_parsed_from_spider.get('orderBy')):
return True
for cond in sql_query_parsed_from_spider['where']:
if (isinstance(cond, tuple) and (WHERE_OPS[cond[1]] == '=') ... |
class Discrete(Space):
def __init__(self, n):
self._n = n
def n(self):
return self._n
def sample(self):
return np.random.randint(self.n)
def contains(self, x):
x = np.asarray(x)
return ((x.shape == ()) and (x.dtype.kind == 'i') and (x >= 0) and (x < self.n))
d... |
def execute_with_timeout(fn, args=None, kwargs=None, timeout=None, fail_if_no_timer=True, signal_type=_DEFAULT_SIGNAL_TYPE, timer_type=_DEFAULT_TIMER_TYPE, timeout_exception_cls=TimeoutError):
if (args is None):
args = empty_tuple
if (kwargs is None):
kwargs = empty_dict
if ((timeout is None... |
class ProjectIssueResourceWeightEventManager(RetrieveMixin, RESTManager):
_path = '/projects/{project_id}/issues/{issue_iid}/resource_weight_events'
_obj_cls = ProjectIssueResourceWeightEvent
_from_parent_attrs = {'project_id': 'project_id', 'issue_iid': 'iid'}
def get(self, id: Union[(str, int)], lazy:... |
class MaskFormerPanopticDatasetMapper(MaskFormerSemanticDatasetMapper):
def __init__(self, is_train=True, *, augmentations, image_format, ignore_label, size_divisibility):
super().__init__(is_train, augmentations=augmentations, image_format=image_format, ignore_label=ignore_label, size_divisibility=size_div... |
class TestEntropy(unittest.TestCase):
def test_petrosian_fd(self):
pfd = petrosian_fd(RANDOM_TS)
petrosian_fd(list(RANDOM_TS))
self.assertEqual(np.round(pfd, 3), 1.03)
assert_equal(aal(petrosian_fd, axis=1, arr=data), petrosian_fd(data))
assert_equal(aal(petrosian_fd, axis=0,... |
def context_decorator(ctx, func):
assert (not (callable(ctx) and hasattr(ctx, '__enter__'))), f'Passed in {ctx} is both callable and also a valid context manager (has __enter__), making it ambiguous which interface to use. If you intended to pass a context manager factory, rewrite your call as context_decorator(la... |
class SymbolBase():
name = None
def __init__(self):
self.value = None
self.first = None
self.second = None
self.third = None
def nud(self, parser):
raise SyntaxError(('Syntax error (%r).' % self.name))
def led(self, left, parser):
raise SyntaxError(('Unkno... |
class XOSLExchangeCalendar(TradingCalendar):
name = 'XOSL'
tz = timezone('Europe/Oslo')
open_times = ((None, time(9, 1)),)
close_times = ((None, time(16, 20)),)
regular_early_close = time(13)
def regular_holidays(self):
return HolidayCalendar([NewYearsDay, MaundyThursday, GoodFriday, Eas... |
def main():
args = create_argparser().parse_args()
dist_util.setup_dist()
logger.configure(dir=args.save_dir)
logger.log('creating model and diffusion...')
(model, diffusion) = create_model_and_diffusion(image_size=args.img_size, dataset=args.dataset, **args_to_dict(args, model_and_diffusion_default... |
class Vgg16Net(nn.Module):
def __init__(self, requires_grad=False, gpu_ids=[]):
super(Vgg16Net, self).__init__()
self.gpu_ids = gpu_ids
model = [Vgg16(requires_grad=requires_grad)]
self.model = nn.Sequential(*model)
def forward(self, input):
if (self.gpu_ids and isinstanc... |
_funcify.register(ExtractDiag)
def jax_funcify_ExtractDiag(op, **kwargs):
offset = op.offset
axis1 = op.axis1
axis2 = op.axis2
def extract_diag(x, offset=offset, axis1=axis1, axis2=axis2):
return jnp.diagonal(x, offset=offset, axis1=axis1, axis2=axis2)
return extract_diag |
def test_swap():
(swap_circuit, _) = SwapTest(n=5).as_composite_bloq().to_cirq_circuit(x=cirq.LineQubit.range(5), y=cirq.LineQubit.range(100, 105), qubit_manager=cirq.ops.SimpleQubitManager())
op = next(swap_circuit.all_operations())
swap_decomp_circuit = cirq.Circuit(cirq.decompose_once(op))
should_be ... |
class DiagGaussian(nn.Module):
def __init__(self, latent_dim, output_dim, unbounded=False, conditioned_sigma=False, max_mu=1.0, sigma_min=(- 20), sigma_max=2):
super().__init__()
self.mu = nn.Linear(latent_dim, output_dim)
self._c_sigma = conditioned_sigma
if conditioned_sigma:
... |
class WorkspaceMixin(abc.ABC, Generic[T]):
def __init__(self, *args: object, **kwargs: object) -> None:
super().__init__(*args, **kwargs)
def workspace_opts(self) -> runopts:
return runopts()
def build_workspace_and_update_role(self, role: Role, workspace: str, cfg: Mapping[(str, CfgVal)]) -... |
def test_asyncio_mark_respects_parametrized_loop_policies(pytester: pytest.Pytester):
pytester.makepyfile(dedent(' import asyncio\n\n import pytest\n\n (\n scope="class",\n params=[\n asyncio.DefaultEventLoopPolicy(),\n ... |
def make_segs(seqs, lens, labs, talabs, seg_len, seg_shift, rand_seg):
segs = []
nsegs = []
for (seq, l, lab, talab) in zip(seqs, lens, labs, talabs):
nseg = (((l - seg_len) // seg_shift) + 1)
nsegs.append(nseg)
if rand_seg:
starts = np.random.choice(xrange(((l - seg_len)... |
class SpatialSoftmax(torch.nn.Module):
def __init__(self, height, width, channel, temperature=None, data_format='NCHW'):
super(SpatialSoftmax, self).__init__()
self.data_format = data_format
self.height = height
self.width = width
self.channel = channel
if temperature... |
class IBKRBorrowFeesSlippageTestCase(unittest.TestCase):
('moonshot.slippage.borrowfee.get_ibkr_borrow_fees_reindexed_like')
def test_borrow_fees_slippage(self, mock_get_ibkr_borrow_fees_reindexed_like):
positions = pd.DataFrame({'FI12345': [0.1, 0, (- 0.2), (- 0.2), (- 0.1), 0.5, (- 0.25)], 'FI23456': ... |
class TestOpenFont(EndianTest):
def setUp(self):
self.req_args_0 = {'fid': , 'name': 'foofont'}
self.req_bin_0 = b'-\x00\x00\x056&\x1b\xf5\x00\x07\x00\x00foofont\x00'
def testPackRequest0(self):
bin = request.OpenFont._request.to_binary(*(), **self.req_args_0)
self.assertBinaryEq... |
class PPMConcat(nn.ModuleList):
def __init__(self, pool_scales=(1, 3, 6, 8)):
super(PPMConcat, self).__init__([nn.AdaptiveAvgPool2d(pool_scale) for pool_scale in pool_scales])
def forward(self, feats):
ppm_outs = []
for ppm in self:
ppm_out = ppm(feats)
ppm_outs.a... |
def test_validate_well_structured_non_term_meas():
(q0, q1) = cirq.LineQubit.range(2)
circuit = cirq.Circuit([cirq.Moment([cirq.PhasedXPowGate(phase_exponent=0).on(q0)]), cirq.Moment([cirq.PhasedXPowGate(phase_exponent=0.5).on(q0)]), cirq.measure(q0, q1, key='z'), cirq.Moment([cg.SYC(q0, q1)])])
with pytest... |
class Effect8227(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Mining')), 'miningAmount', ship.getModifiedItemAttr('miningBargeBonusOreMiningYield'), skill='Mining Barge', **kwargs) |
def find_vertical_start(horizontal_start, num_sides):
horizontal_angles = []
vertical_start = (horizontal_start + 90)
for i in range(1, num_sides):
angle = ((horizontal_start + 90) + ((i * 360.0) / num_sides))
if (angle >= 270):
vertical_start = (angle - 360)
break
... |
def Inference(loader, test_loader, model, global_step):
print('Starting Inference...')
start_time = time.time()
model.eval()
candidates = {}
references = {}
cand_lists = []
ref_lists = []
with torch.no_grad():
for (bi, batch) in enumerate(loader):
(img1, img2, gts, Im... |
class NetworkImageNet(nn.Module):
def __init__(self, C, num_classes, layers, auxiliary, genotype):
super(NetworkImageNet, self).__init__()
self._layers = layers
self._auxiliary = auxiliary
self.drop_path_prob = 0
self.stem0 = nn.Sequential(nn.Conv2d(3, (C // 2), kernel_size=3... |
class BeatServer(StatelessServer):
def __init__(self, application, channel_layer, beat_config, max_applications=1000):
super().__init__(application, max_applications)
self.channel_layer = channel_layer
if (self.channel_layer is None):
raise ValueError('Channel layer is not valid'... |
def test_comprehension():
d_comp = dict(((str((k * k)), ([v] * (1 << 17))) for (v, k) in enumerate(range(99, 111))))
l_comp = [([i] * (i << 9)) for i in range(99)]
del l_comp
del d_comp
def hh(x=1):
s_comp = set(((('Z',) * (k << 13)) for k in range(x, (19 + (2 * x)))))
return s_comp
... |
def _get_interpreters_posix():
found = []
def isPathValidPythonExe(filename):
fname = os.path.split(filename)[1]
return (fname.startswith(('python', 'pypy')) and (not fname.count('config')) and (len(fname) < 16) and os.path.isfile(filename))
for searchpath in ['/usr/bin', '/usr/local/bin', '... |
class FillPoly(rq.Request):
_request = rq.Struct(rq.Opcode(69), rq.Pad(1), rq.RequestLength(), rq.Drawable('drawable'), rq.GC('gc'), rq.Set('shape', 1, (X.Complex, X.Nonconvex, X.Convex)), rq.Set('coord_mode', 1, (X.CoordModeOrigin, X.CoordModePrevious)), rq.Pad(2), rq.List('points', structs.Point)) |
def compute_ne(ce_sum: torch.Tensor, weighted_num_samples: torch.Tensor, pos_labels: torch.Tensor, neg_labels: torch.Tensor, num_groups: int, eta: float) -> torch.Tensor:
result_ne = torch.zeros(num_groups)
for group in range(num_groups):
mean_label = (pos_labels[group] / weighted_num_samples[group])
... |
def _unwrap_value_from_subclass(result: Value, ctx: AttrContext) -> Value:
if ((not isinstance(result, KnownValue)) or ctx.skip_unwrap):
return result
cls_val = result.val
if (qcore.inspection.is_classmethod(cls_val) or inspect.ismethod(cls_val) or inspect.isfunction(cls_val) or isinstance(cls_val, ... |
class Migration(migrations.Migration):
dependencies = [('conditions', '0015_move_attribute_to_attributeentity')]
operations = [migrations.AlterField(model_name='condition', name='relation', field=models.CharField(choices=[('eq', 'is equal to (==)'), ('neq', 'is not equal to (!=)'), ('contains', 'contains'), ('g... |
def install_pip(home):
pip_path = (home + '/Scripts/pip.exe')
python_path = (home + '/python.exe')
if exists(pip_path):
print('pip already installed.')
else:
print('Installing pip...')
download_file(GET_PIP_URL, GET_PIP_PATH)
print('Executing:', python_path, GET_PIP_PATH)... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--mrdef-csv-file', type=str, default='./data/MRDEF_name.csv', help='Path to json filewith training data')
parser.add_argument('--umls-kg-file', type=str, default='./data/umls_kg.csv', help='Path to json file with validation data')
... |
class TestMetaLabels(object):
def setup_method(self):
testInst = pysat.Instrument('pysat', 'testing')
self.meta_labels = testInst.meta.labels
self.meta = pysat.Meta()
return
def teardown_method(self):
del self.meta, self.meta_labels
return
def test_default_lab... |
class GetCommonChats():
async def get_common_chats(self: 'pyrogram.Client', user_id: Union[(int, str)]) -> List['types.Chat']:
peer = (await self.resolve_peer(user_id))
if isinstance(peer, raw.types.InputPeerUser):
r = (await self.invoke(raw.functions.messages.GetCommonChats(user_id=peer... |
def truncate_to_first_stop_token(tokens: torch.LongTensor, stop_ids: List[Union[(int, List[int])]]) -> torch.LongTensor:
if (not stop_ids):
return tokens
stop_ids: List[torch.LongTensor] = [torch.LongTensor(([stop_id] if (not isinstance(stop_id, list)) else stop_id)) for stop_id in stop_ids]
for i i... |
def build_word_vec(word_list, model_word2vec):
matrix_word2vec = []
igNoreList = list()
for (i, word) in enumerate(word_list):
print(i, word)
try:
matrix_word2vec.append(model_word2vec[word])
except:
igNoreList.append(word)
randArray = np.random.ra... |
(bdd.parsers.parse('the per-domain option {option} should be set to {value} for {pattern}'))
def check_option_per_domain(quteproc, option, value, pattern, server):
pattern = pattern.replace('(port)', str(server.port))
actual_value = quteproc.get_setting(option, pattern=pattern)
assert (actual_value == value... |
def migrate_old_config():
active = []
old_keys = ['songsmenuplugins', 'eventplugins', 'editingplugins', 'playorderplugins']
for key in old_keys:
key = ('active_' + key)
try:
active.extend(config.get('plugins', key).splitlines())
except config.Error:
pass
... |
class TestMLTGWD(TestMLT):
def eval(self):
txt_name = '{}.txt'.format(self.cfgs.VERSION)
real_test_img_list = self.get_test_image()
gwd = build_whole_network.DetectionNetworkGWD(cfgs=self.cfgs, is_training=False)
self.test_mlt(det_net=gwd, real_test_img_list=real_test_img_list, txt_n... |
def accumulate_cv_results(trained_model_folder, merged_output_folder: str, folds: Union[(List[int], Tuple[(int, ...)])], num_processes: int=default_num_processes, overwrite: bool=True):
if (overwrite and isdir(merged_output_folder)):
shutil.rmtree(merged_output_folder)
maybe_mkdir_p(merged_output_folder... |
def test_unused_udp_port_selects_unused_port(pytester: Pytester):
pytester.makepyfile(dedent(' .asyncio\n async def test_unused_udp_port_fixture(unused_udp_port):\n class Closer:\n def connection_made(self, transport):\n pass\n\n ... |
def downloadUUID(accessurl, uuid):
downloadFile(accessurl.format(filename=f'{uuid}_50k.dam'), f'{uuid}_50k.dam')
shutil.copy(f'{uuid}_50k.dam', f'..{os.path.sep}{uuid}_50k.dam')
cur_file = ''
try:
for i in range(1000):
cur_file = accessurl.format(filename=f'{uuid}_50k_texture_jpg_hig... |
def main(args):
if (len(args) != 1):
dsz.ui.Echo('Usage: reproject <project>', dsz.ERROR)
return 0
f = open(os.path.join(ops.LOGDIR, 'project.txt'), 'w')
f.write(args[0].upper())
f.close()
dsz.ui.Echo(("Target %s's project has been changed to %s" % (ops.TARGET_ADDR, args[0].upper()))... |
class _ArcIteratorBase(object):
def __init__(self, fst, state):
if (not fst._valid_state_id(state)):
raise IndexError('State index out of range')
super(_ArcIteratorBase, self).__init__(fst, state)
def __iter__(self):
while (not self._done()):
(yield self._value())... |
def tasklist_manager(request, manager_nospawn, override_xdg, monkeypatch):
monkeypatch.setattr('libqtile.widget.tasklist.has_xdg', override_xdg)
config = getattr(request, 'param', dict())
class TasklistConfig(Config):
auto_fullscreen = True
groups = [libqtile.config.Group('a'), libqtile.conf... |
class _ArchX86(Arch):
NAME = 'x86'
INS_PTR = Reg('eip')
STK_PTR = Reg('esp')
_CSD = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_32)
nop_instruction = b'\x90'
class optypes(IntEnum):
INVALID = x86_const.X86_OP_INVALID
IMM = x86_const.X86_OP_IMM
REG = x86_const.X86_O... |
(repr=True, frozen=True)
class BatchTensorDescriptor(TensorDescriptor):
def __init__(self, *instance_size, **kwargs):
if ((len(instance_size) == 1) and isinstance(instance_size[0], (list, tuple, torch.Size))):
instance_size = instance_size[0]
super().__init__((None, *instance_size), **kw... |
def _parse_constraint(constraints: str, *, is_marker_constraint: bool=False) -> VersionConstraint:
if (constraints == '*'):
from poetry.core.constraints.version.version_range import VersionRange
return VersionRange()
or_constraints = re.split('\\s*\\|\\|?\\s*', constraints.strip())
or_groups... |
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
tokenizer = tokenization.FullTokenizer(vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
input_files = []
for input_pattern in FLAGS.input_file.split(','):
input_files.extend(tf.gfile.Glob(input_pattern))
tf.logging.info('*... |
class RealFsTestCase(fake_filesystem_unittest.TestCase, RealFsTestMixin):
def __init__(self, methodName='runTest'):
fake_filesystem_unittest.TestCase.__init__(self, methodName)
RealFsTestMixin.__init__(self)
def setUp(self):
RealFsTestMixin.setUp(self)
self.cwd = os.getcwd()
... |
class ServerAction(actions.BaseAction):
name = 'server'
security = 'server'
parent_parsers = [actions.RESTRICT_PARSER]
def add_action_subparser(cls, sub_handler):
subparser = super().add_action_subparser(sub_handler)
subparser.add_argument('--debug', action='store_true', help='Allow for ... |
def cache_only(func):
import pynag.Model
def wrap(*args, **kwargs):
pynag.Model.ObjectFetcher._cache_only = True
try:
return func(*args, **kwargs)
finally:
pynag.Model.ObjectFetcher._cache_only = False
wrap.__name__ = func.__name__
wrap.__module__ = func._... |
_flags(floatX='float64')
def test_debugprint_sitsot():
k = iscalar('k')
A = dvector('A')
(result, updates) = pytensor.scan(fn=(lambda prior_result, A: (prior_result * A)), outputs_info=pt.ones_like(A), non_sequences=A, n_steps=k)
final_result = result[(- 1)]
output_str = debugprint(final_result, fil... |
class BeaverConfig():
def __init__(self, args, logger=None):
self._logger = (logger or logging.getLogger(__name__))
self._logger.debug(('Processing beaver portion of config file %s' % args.config))
self._section_defaults = {'add_field': '', 'add_field_env': '', 'debug': '0', 'discover_interv... |
def _check_sym_funcs():
seen_results = set()
for (name, f) in _symm_funcs.items():
n = len(name)
query = list(range(4, (4 + n)))
result = f(query)
x = tuple(sorted(result))
assert (x not in seen_results), x
seen_results.add(x)
seen_terms = set()
fo... |
def test_private(hatch, helpers, temp_dir_data, path_append, dist_name, mocker):
dist_dir = (((temp_dir_data / 'data') / 'pythons') / dist_name)
python_path = (dist_dir / get_distribution(dist_name).python_path)
install = mocker.patch('hatch.python.core.PythonManager.install', return_value=mocker.MagicMock(... |
def measure_UIQMs(dir_name, file_ext=None):
paths = sorted(glob(join(dir_name, '*.*')))
if file_ext:
paths = [p for p in paths if p.endswith(file_ext)]
uqims = []
for img_path in paths:
im = Image.open(img_path).resize((im_w, im_h))
uqims.append(getUIQM(np.array(im)))
return ... |
def scale_linestrength_eq(df, Tref, Tgas):
print('Scaling equilibrium linestrength')
def _calc_Q(molecule, iso, T_ref, T_gas):
Qref = get_Qgas(molecule, iso, T_ref)
Qgas = get_Qgas(molecule, iso, T_gas)
return (Qref, Qgas)
id_set = df.id.unique()
id = list(id_set)[0]
molecule... |
class MobileNetFeaturePyramidExtractor(SSDMobileNetV1FeatureExtractor):
def extract_features(self, preprocessed_inputs, init_extraction=False):
if init_extraction:
preprocessed_inputs.get_shape().assert_has_rank(4)
shape_assert = tf.Assert(tf.logical_and(tf.greater_equal(tf.shape(pre... |
.unit()
.xfail(reason='See #377.')
def test_live_execution_skips_do_not_crowd_out_displayed_tasks(capsys, tmp_path):
path = tmp_path.joinpath('task_module.py')
task = Task(base_name='task_example', path=path, function=(lambda x: x))
task.name = 'task_module.py::task_example'
live_manager = LiveManager()... |
class TestNumaCollector(CollectorTestCase):
def setUp(self):
config = get_collector_config('NumaCollector', {'interval': 10, 'bin': 'true'})
self.collector = NumaCollector(config, None)
def test_import(self):
self.assertTrue(NumaCollector)
(Collector, 'publish')
def test(self, pu... |
('tag1', 'tag2')
class TestDjangoTagsToPytestMarkers(SimpleTestCase):
(autouse=True)
def gimme_my_markers(self, request: pytest.FixtureRequest) -> None:
self.markers = {m.name for m in request.node.iter_markers()}
('tag3', 'tag4')
def test_1(self) -> None:
assert (self.markers == {'tag1'... |
def visualize_batch(batch):
if (len(batch.shape) == 4):
if (batch.shape[3] == 2):
batch = [flow_to_image(batch[i]) for i in range(batch.shape[0])]
cv2.imshow('Optical flow set', np.hstack(batch))
else:
batch = [batch[i] for i in range(batch.shape[0])]
... |
def omniglotfs():
base = torch.load((args.dataset_path + 'omniglot/base.pt'))
base_data = base.reshape((- 1), base.shape[2], base.shape[3], base.shape[4]).float()
base_targets = torch.arange(base.shape[0]).unsqueeze(1).repeat(1, base.shape[1]).reshape((- 1))
val = torch.load((args.dataset_path + 'omnigl... |
class TestPegasosQSVC(QiskitMachineLearningTestCase):
def setUp(self):
super().setUp()
algorithm_globals.random_seed = 10598
self.q = 2
self.tau = 100
self.feature_map = ZFeatureMap(feature_dimension=self.q, reps=1)
(sample, label) = make_blobs(n_samples=20, n_feature... |
def set_application_info(app):
from quodlibet._init import is_init
assert is_init()
from gi.repository import Gtk, GLib
assert app.process_name
set_process_title(app.process_name)
GLib.idle_add(set_process_title, app.process_name)
assert app.id
GLib.set_prgname(app.id)
assert app.nam... |
class GroupbySize(GroupbyAggregation):
def on_new(self, acc, new, grouper=None):
g = self.grouped(new, grouper=grouper)
result = acc.add(g.size(), fill_value=0)
result = result.astype(int)
result.index.name = acc.index.name
return (result, result)
def on_old(self, acc, ol... |
def clean_paragraphs(document):
if (document['id'] in BLACKLIST):
return None
html_pattern = re.compile('(</a>)|(<a.*?href.*?>)')
def remove_tags(text):
return re.sub(html_pattern, '', text)
cleaned_pars = []
for par_sentences in document['text'][1:]:
clean_par = []
f... |
class MemoryDB(BaseDB):
kv_store: Dict[(bytes, bytes)] = None
def __init__(self, kv_store: Dict[(bytes, bytes)]=None) -> None:
if (kv_store is None):
self.kv_store = {}
else:
self.kv_store = kv_store
def __getitem__(self, key: bytes) -> bytes:
return self.kv_s... |
def upgrade_state_dict_for_deltalm(state_dict: Dict[(str, Any)], pretrained_deltalm_checkpoint: str, is_encoder=True) -> Dict[(str, Any)]:
if (not os.path.exists(pretrained_deltalm_checkpoint)):
raise IOError('Model file not found: {}'.format(pretrained_deltalm_checkpoint))
with open(pretrained_deltalm_... |
def infer_constraints_if_possible(template: Type, actual: Type, direction: int) -> (list[Constraint] | None):
if ((direction == SUBTYPE_OF) and (not mypy.subtypes.is_subtype(erase_typevars(template), actual))):
return None
if ((direction == SUPERTYPE_OF) and (not mypy.subtypes.is_subtype(actual, erase_t... |
_loss('bce')
class BinaryCrossEntropyLoss(nn.Module):
def __init__(self):
super().__init__()
def forward(self, sample_list, model_output):
scores = model_output['scores']
targets = sample_list['targets']
loss = F.binary_cross_entropy(scores, targets, reduction='mean')
ret... |
def test_buffer_position(buffer_):
for _ in range(10):
position = [random.uniform((- 10.0), 10.0) for _ in range(3)]
buffer_.position = position
if buffer_.is3d:
assert iter_almost_equal(buffer_.position, position)
else:
assert (buffer_.position == (0, 0, 0)) |
class Prepared():
normalized = None
legacy_normalized = None
def __init__(self, name):
self.name = name
if (name is None):
return
self.normalized = self.normalize(name)
self.legacy_normalized = self.legacy_normalize(name)
def normalize(name):
return re... |
def set_up_clipboard(is_input):
command = []
if sys.platform.startswith('linux'):
if cmd_exists('xclip'):
command.append('xclip')
if is_input:
command.append('-selection')
command.append('c')
else:
command.append('-selec... |
_db
('score_index', [1, 2, 3, 4])
def test_submit_vote(graphql_client, user, conference_factory, submission_factory, score_index, requests_mock):
graphql_client.force_login(user)
conference = conference_factory(active_voting=True)
submission = submission_factory(conference=conference)
requests_mock.post... |
.parametrize('username,password', users)
.parametrize('export_format', export_formats)
def test_detail_export(db, client, username, password, export_format):
client.login(username=username, password=password)
instance = Page.objects.first()
url = ((reverse(urlnames['detail_export'], args=[instance.pk]) + ex... |
def _dtype_to_pytorch_dtype(dtype: dt.DType) -> torch.dtype:
torch_dtype_name = ('bool' if (dtype.name == 'boolean') else dtype.name)
if (not hasattr(torch, torch_dtype_name)):
raise ValueError(f"Can't convert {dtype} to PyTorch")
torch_dtype = getattr(torch, torch_dtype_name)
return torch_dtype |
def test(model, device, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for (data, target) in test_loader:
(data, target) = (data.to(device), target.to(device))
output = model(data)
test_loss += F.nll_loss(output, target, reduction='... |
class BatchEncoding(UserDict):
def __init__(self, data: Optional[Dict[(str, Any)]]=None, encoding: Optional[Union[(EncodingFast, Sequence[EncodingFast])]]=None, tensor_type: Union[(None, str, TensorType)]=None, prepend_batch_axis: bool=False, n_sequences: Optional[int]=None):
super().__init__(data)
... |
def substitute_variables(quadratic_program: QuadraticProgram, constants: Optional[Dict[(Union[(str, int)], float)]]=None, variables: Optional[Dict[(Union[(str, int)], Tuple[(Union[(str, int)], float)])]]=None) -> QuadraticProgram:
subs = {}
if constants:
for (i, v) in constants.items():
i_2 ... |
def check_bitdepth_rescale(palette, bitdepth, transparent, alpha, greyscale):
if palette:
if (len(bitdepth) != 1):
raise ProtocolError('with palette, only a single bitdepth may be used')
(bitdepth,) = bitdepth
if (bitdepth not in (1, 2, 4, 8)):
raise ProtocolError('wi... |
class ContrastiveLoss(nn.Module):
def __init__(self, model: SentenceTransformer, distance_metric=SiameseDistanceMetric.COSINE_DISTANCE, margin: float=0.5, size_average: bool=True):
super(ContrastiveLoss, self).__init__()
self.distance_metric = distance_metric
self.margin = margin
sel... |
class Story(NameSlugModel, ContentManageable):
company_name = models.CharField(max_length=500)
company_url = models.URLField(verbose_name='Company URL')
company = models.ForeignKey(Company, related_name='success_stories', blank=True, null=True, on_delete=models.CASCADE)
category = models.ForeignKey(Stor... |
def save_json_predictions(opts, cost, sample_idx, k_low, features, cls_list, cls_names, img_ids):
num_classes = len(cls_list)
json_predictions = {}
for cls in range(num_classes):
suffix = 'sample{}_k{}'.format((sample_idx + 1), k_low)
model_file = svm_helper.get_low_shot_output_file(opts, cl... |
def rxn_template(rxn_smiles, templates):
rxn_parts = split_rxn_parts(rxn_smiles)
(reactants, agents, products) = (rxn_parts[0], rxn_parts[1], rxn_parts[2])
temp_match = None
for t in templates:
agents_match = None
products_match = None
reactants_match = True
for r in reac... |
def orders_to_selection(orders, pad=1.0):
selection = []
nslc_to_deltat = {}
for order in sorted(orders, key=orders_sort_key):
selection.append((order.codes.nslc + (order.tmin, order.tmax)))
nslc_to_deltat[order.codes.nslc] = order.deltat
selection = combine_selections(selection)
sel... |
class Scenario(ScenarioGenerator):
def __init__(self):
super().__init__()
def road(self, **kwargs):
planview = xodr.PlanView()
planview.add_fixed_geometry(xodr.Line(100), 0, 0, 0)
planview.add_fixed_geometry(xodr.Arc(0.01, length=100), 100, 0, 0)
lanes = xodr.Lanes()
... |
def lazy_apply(module: torch.nn.Module, fn: Callable[([torch.nn.Module], None)]) -> torch.nn.Module:
if (not hasattr(module, '_functions_to_lazy_apply')):
module._functions_to_lazy_apply = []
if (not hasattr(module, '_lazy_apply_hook')):
module._lazy_apply_hook = module.register_forward_hook(_ap... |
class Effect6233(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Energy Neutralizer')), 'falloffEffectiveness', src.getModifiedItemAttr('eliteBonusReconShip3'), skill='Recon Ships', **kwargs) |
def generate_summaries_or_translations(examples: List[str], out_file: str, model_name: str, batch_size: int=8, device: str=DEFAULT_DEVICE, fp16=False, task='summarization', prefix=None, **generate_kwargs) -> Dict:
fout = Path(out_file).open('w', encoding='utf-8')
model_name = str(model_name)
model = AutoMod... |
class ProjectMergeRequestApprovalRule(SaveMixin, ObjectDeleteMixin, RESTObject):
_repr_attr = 'name'
id: int
approval_rule_id: int
merge_request_iid: int
_
def save(self, **kwargs: Any) -> None:
self.approval_rule_id = self.id
self.merge_request_iid = self._parent_attrs['mr_iid']... |
_rewriter([GenGammaRV])
def generalized_gamma_from_gamma(fgraph, node):
(*other_inputs, alpha, p, lambd) = node.inputs
(next_rng, g) = _gamma.make_node(*other_inputs, (alpha / p), ones_like(lambd)).outputs
g = ((g ** reciprocal(p)) * lambd)
return [next_rng, cast(g, dtype=node.default_output().dtype)] |
def test_classify():
res_dir = (this_dir / 'scratch_classify')
result_paths = list(res_dir.glob('**/{}'.format(cfg.results_file_name)))
for (rr, rpath) in enumerate(result_paths):
full_results = load_results(rpath)
print('testing results from {}'.format(rpath))
num_datasets = len(ful... |
class HistoricalRestrictions(Restrictions):
def __init__(self, restrictions):
self._restrictions_by_asset = {asset: sorted(restrictions_for_asset, key=(lambda x: x.effective_date)) for (asset, restrictions_for_asset) in iteritems(groupby((lambda x: x.asset), restrictions))}
def is_restricted(self, asset... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.