code stringlengths 281 23.7M |
|---|
def ql_syscall_sys_cpupage_get(ql: Qiling, index, *args, **kw):
if (index == ):
return ql.os.cpupage_addr
elif (index == 1):
return ql.mem.read_ptr((ql.os.cpupage_addr + 4), 4)
elif (index == 2):
return ql.os.syspage_addr
ql.log.warning(f'ql_syscall_sys_cpupage_get (index {index:... |
def memory_stream_pump(memory_send_stream: MemorySendStream, memory_receive_stream: MemoryReceiveStream, *, max_bytes: (int | None)=None) -> bool:
try:
data = memory_send_stream.get_data_nowait(max_bytes)
except _core.WouldBlock:
return False
try:
if (not data):
memory_re... |
class ProgressMeter(object):
def __init__(self, num_batches, meters, prefix=''):
self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
self.meters = meters
self.prefix = prefix
def display(self, batch):
entries = [(self.prefix + self.batch_fmtstr.format(batch))]
entries... |
def test_wrapper_bug():
with safer.writer(FILENAME) as fp:
fp.write('hello, world')
assert (FILENAME.read_text() == 'hello, world')
fp = open(FILENAME, 'w')
with safer.writer(fp, close_on_exit=True):
fp.write('hello, world')
assert (FILENAME.read_text() == 'hello, world') |
class FixtureFactory(object):
def __init__(self):
self._setup_stack = SetupStack()
self._context_managers = {}
self._fixtures = {}
def register_context_manager(self, name, context_manager):
self._context_managers[name] = context_manager
def get_fixture(self, name, add_teardow... |
_flags(floatX='float64')
def test_debugprint_mitmot():
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 = pytensor.grad(result[(- 1)].sum(), A)
output_str = debu... |
def test_admin_session_download_layout_description_no_spoiler(clean_database, mock_emit_session_update, flask_app, mocker):
mock_layout_description: PropertyMock = mocker.patch('randovania.server.database.MultiplayerSession.layout_description', new_callable=PropertyMock)
user1 = database.User.create(id=1234, na... |
_fixtures(WebFixture, ExampleFixture.layout)
def test_layout(web_fixture, layout_scenario):
fixture = layout_scenario
fixture.start_example_app()
web_fixture.driver_browser.open('/')
web_fixture.driver_browser.type(XPath.input_labelled('Email address'), 'johndoe')
assert web_fixture.driver_browser.w... |
class ProxyEnv(Env):
def __init__(self, wrapped_env):
self._wrapped_env = wrapped_env
def wrapped_env(self):
return self._wrapped_env
def reset(self):
return self._wrapped_env.reset()
def action_space(self):
return self._wrapped_env.action_space
def observation_space(... |
def digit_version(version_str):
digit_version = []
for x in version_str.split('.'):
if x.isdigit():
digit_version.append(int(x))
elif (x.find('rc') != (- 1)):
patch_version = x.split('rc')
digit_version.append((int(patch_version[0]) - 1))
digit_ver... |
def on_text(text):
try:
index = (int(text) - 1)
except ValueError:
return
if (not (0 <= index < len(tablets))):
return
name = tablets[index].name
try:
canvas = tablets[index].open(window)
except pyglet.input.DeviceException:
print(f'Failed to open tablet {... |
class TermGraph(object):
def __init__(self, terms):
self.graph = nx.DiGraph()
self._frozen = False
parents = set()
for term in itervalues(terms):
self._add_to_graph(term, parents)
assert (not parents)
self._outputs = terms
self._frozen = True
... |
class ErnieMConfig(PretrainedConfig):
model_type = 'ernie_m'
attribute_map: Dict[(str, str)] = {'dropout': 'classifier_dropout', 'num_classes': 'num_labels'}
def __init__(self, vocab_size: int=250002, hidden_size: int=768, num_hidden_layers: int=12, num_attention_heads: int=12, intermediate_size: int=3072, ... |
(scope='module')
def reply_keyboard_markup():
return ReplyKeyboardMarkup(TestReplyKeyboardMarkupBase.keyboard, resize_keyboard=TestReplyKeyboardMarkupBase.resize_keyboard, one_time_keyboard=TestReplyKeyboardMarkupBase.one_time_keyboard, selective=TestReplyKeyboardMarkupBase.selective, is_persistent=TestReplyKeyboar... |
_ephem
def test_pyephem_physical_dst(expected_solpos, golden):
times = pd.date_range(datetime.datetime(2003, 10, 17, 13, 30, 30), periods=1, freq='D', tz=golden.tz)
ephem_data = solarposition.pyephem(times, golden.latitude, golden.longitude, pressure=82000, temperature=11)
expected_solpos.index = times
... |
class RELATIONSHIP_TYPE():
AUDIO = '
A_F_CHUNK = '
CALC_CHAIN = '
CERTIFICATE = '
CHART = '
CHARTSHEET = '
CHART_USER_SHAPES = '
COMMENTS = '
COMMENT_AUTHORS = '
CONNECTIONS = '
CONTROL = '
CORE_PROPERTIES = '
CUSTOM_PROPERTIES = '
CUSTOM_PROPERTY = '
CUSTOM_X... |
class EpisodicCPUDataset():
def __init__(self, data, num_classes, transforms=[], episode_size=args.batch_size, use_hd=False):
self.data = data
if torch.is_tensor(data):
self.length = data.shape[0]
else:
self.length = len(self.data)
self.episode_size = ((episod... |
class TransLog(object):
def __init__(self):
self.layers = {}
self.detail_layers = {}
self.detail_blobs = {}
self._blobs = Blob_LOG()
self._blobs_data = []
self.cnet = caffe_net.Caffemodel('')
self.debug = True
def init(self, inputs):
self.add_blobs... |
def expected_flattened(prefix: str) -> Dict[(str, Any)]:
flattened = {'foo': 0, 'bar': 1, 'baz/0': 2, 'baz/1': 3, 'baz/2/qux': 4, 'baz/2/quxx/0': 5, 'baz/2/quxx/1/quuz': 6, 'baz/2/quxx/1/corge/0': 7, 'baz/2/quxx/1/corge/1': 8, 'baz/2/quxx/1/corge/2': 9, 'x%2Fy/%25a%2Fb': 10, 'dict_with_colliding_keys': {'0': {'1': ... |
class ImageExporter(Exporter):
Name = 'Image File (PNG, TIF, JPG, ...)'
allowCopy = True
def __init__(self, item):
Exporter.__init__(self, item)
tr = self.getTargetRect()
if isinstance(item, QtWidgets.QGraphicsItem):
scene = item.scene()
else:
scene = ... |
class DepthwiseSeparableASPPModule(ASPPModule):
def __init__(self, **kwargs):
super(DepthwiseSeparableASPPModule, self).__init__(**kwargs)
for (i, dilation) in enumerate(self.dilations):
if (dilation > 1):
self[i] = DepthwiseSeparableConvModule(self.in_channels, self.chan... |
def test_speedcondition():
cond = OSC.SpeedCondition(1, OSC.Rule.lessThan, OSC.DirectionalDimension.lateral)
prettyprint(cond.get_element())
cond2 = OSC.SpeedCondition(1, OSC.Rule.lessThan, OSC.DirectionalDimension.lateral)
cond3 = OSC.SpeedCondition(2, OSC.Rule.lessThan)
assert (cond == cond2)
... |
def _build_module(cfg, registry, default_args):
assert (isinstance(cfg, dict) and ('type' in cfg))
assert (isinstance(default_args, dict) or (default_args is None))
args = cfg.copy()
obj_type = args.pop('type')
if mmcv.is_str(obj_type):
if (obj_type not in registry.module_dict):
... |
def test_editable_wheel_namespace_package(copy_sample):
td = copy_sample('ns1-pkg')
make_wheel_in((td / 'pyproject.toml'), td, editable=True)
whl_file = (td / 'ns1_pkg-0.1-py2.py3-none-any.whl')
assert_isfile(whl_file)
with unpack(whl_file) as unpacked:
pth_path = Path(unpacked, 'ns1.pkg.pth... |
def _form_master_re(relist, reflags, ldict):
if (not relist):
return []
regex = '|'.join(relist)
try:
lexre = re.compile(regex, (re.VERBOSE | reflags))
lexindexfunc = ([None] * (max(lexre.groupindex.values()) + 1))
for (f, i) in lexre.groupindex.items():
handle = ... |
class Unwrapper(OracleDatabase):
CHAR_MAP_SUBSTITUTION = [61, 101, 133, 179, 24, 219, 226, 135, 241, 82, 171, 99, 75, 181, 160, 95, 125, 104, 123, 155, 36, 194, 40, 103, 138, 222, 164, 38, 30, 3, 235, 23, 111, 52, 62, 122, 63, 210, 169, 106, 15, 233, 53, 86, 31, 177, 77, 16, 120, 217, 117, 246, 188, 65, 4, 129, 97,... |
class TemplateTagTests(BaseTestCase):
def render(self, tmpl, **context):
t = template.Template(tmpl)
return t.render(template.Context(context))
def test_tag(self):
r = self.render('{% load boxes %}{% box "test" %}')
self.assertEqual(r, self.box.content.rendered)
def test_tag_... |
class _DeepLabHead(nn.Module):
def __init__(self, in_channels, nclass, norm_layer=nn.BatchNorm2d, norm_kwargs=None, **kwargs):
super(_DeepLabHead, self).__init__()
self.aspp = _ASPP(in_channels, [12, 24, 36], norm_layer=norm_layer, norm_kwargs=norm_kwargs, **kwargs)
out_channels = 128
... |
class TokenEmbedding(nn.Module):
def __init__(self, charset_size: int, embed_dim: int):
super().__init__()
self.embedding = nn.Embedding(charset_size, embed_dim)
self.embed_dim = embed_dim
def forward(self, tokens: torch.Tensor):
return (math.sqrt(self.embed_dim) * self.embedding... |
('pypyr.moduleloader.get_module')
(Step, 'invoke_step')
def test_run_pipeline_steps_complex_with_skip_str_formatting_false(mock_invoke_step, mock_get_module):
step = Step({'name': 'step1', 'skip': '{key6}'})
context = get_test_context()
original_len = len(context)
with patch_logger('pypyr.dsl', logging.... |
def load_data_and_labels_train(path_train, path_test, categories):
f = codecs.open(path_train, 'r')
train = [x.strip('\n') for x in f.readlines()]
f.close()
clean_train_documents = []
clean_test_documents = []
y_train = []
y_test = []
num_documents = len(train)
for i in range(num_doc... |
(scope='module')
def root_dir(tmp_path_factory):
tmpdir = tmp_path_factory.mktemp('jit-unspill')
if (ProxifyHostFile._spill_to_disk is None):
ProxifyHostFile(worker_local_directory=tmpdir.name, device_memory_limit=1024, memory_limit=1024)
assert (ProxifyHostFile._spill_to_disk is not None)
retur... |
class Effect11401(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Small Projectile Turret')), 'maxRange', ship.getModifiedItemAttr('shipBonusNavyDestroyerMinmatar4'), **kwargs) |
class PickleNode():
def __init__(self, name: str='', path: (Path | None)=None) -> None:
self.name = name
self.path = path
def signature(self) -> str:
raw_key = str(hash_value(self.path))
return hashlib.sha256(raw_key.encode()).hexdigest()
def from_path(cls, path: Path) -> 'Pi... |
def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
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, dat... |
class BacktestTradingSessionBuilder():
def __init__(self, settings: Settings, pdf_exporter: PDFExporter, excel_exporter: ExcelExporter):
self._logger = qf_logger.getChild(self.__class__.__name__)
self._backtest_name = 'Backtest Results'
self._initial_cash =
self._initial_risk = None... |
class TestResourcesApp(unittest.TestCase):
def setUpClass(cls):
import resources_app
cls.AppClass = resources_app.MyApp
def setUp(self):
self.AppClass.log_request = (lambda x, y: None)
self.previouse_dir = os.getcwd()
os.chdir(examples_dir)
def tearDown(self):
... |
def model_processing(model, src_dir, dest_dir, timeseq_len):
train_dir = os.path.join(src_dir, 'train')
test_dir = os.path.join(src_dir, 'test')
dest_train_dir = os.path.join(dest_dir, 'train')
if os.path.exists(dest_train_dir):
print(dest_train_dir, 'already exists')
else:
os.mkdir(... |
class TestClassPath():
.skipif((sys.platform == 'win32'), reason='Windows cannot delete jar while JVM runs')
def test_download_classpath_with_verbose(self, r5_jar_url, r5_jar_sha256, r5_jar_cached, r5_jar_cached_invalid):
sys.argv.extend(['--verbose', '--r5-classpath', r5_jar_cached_invalid])
tr... |
class MultiResolutionDataset(Dataset):
def __init__(self, path, transform=_transform, resolution=256, return_indices=False):
self.env = lmdb.open(path, max_readers=32, readonly=True, lock=False, readahead=False, meminit=False)
if (not self.env):
raise IOError('Cannot open lmdb dataset', ... |
class PartialCompareOutcome():
def __init__(self, error=None):
self.error = error
def __bool__(self):
return (self.error is None)
def __repr__(self):
return 'PartialCompareOutcome(error={!r})'.format(self.error)
def __str__(self):
return ('true' if (self.error is None) el... |
def _read_logo(content):
def _read_logo(pat):
pattern = (pat + ':\\s+\\S+')
data_str = re.compile(pattern).search(content).group()
return data_str.split(':')[1].strip()
info = {}
for pat in ['Version', 'Website']:
info[pat] = _read_logo(pat)
return info |
class SemVerWithVPrefix(Version):
def parse(cls, version: str) -> 'SemVerWithVPrefix':
if (not (version[0] in ('v', 'V'))):
raise ValueError(f"{version!r}: not a valid semantic version tag. Must start with 'v' or 'V'")
return super().parse(version[1:], optional_minor_and_patch=True)
... |
_transform('VisslAutoAugment')
class AutoAugment(ClassyTransform):
def __init__(self, policy_name='v0', magnitude_std=0, **kwargs):
hparams = kwargs
hparams.update(_HPARAMS_DEFAULT)
hparams['magnitude_std'] = magnitude_std
self.policy = auto_augment_policy(policy_name, hparams=hparam... |
class Pad(object):
def __init__(self, padding, fill=0, padding_mode='constant'):
assert isinstance(padding, (numbers.Number, tuple))
assert isinstance(fill, (numbers.Number, str, tuple))
assert (padding_mode in ['constant', 'edge', 'reflect', 'symmetric'])
if (isinstance(padding, Seq... |
class Migration(migrations.Migration):
dependencies = [('core', '0012_currentsong_last_paused')]
operations = [migrations.AlterField(model_name='queuedsong', name='external_url', field=models.CharField(max_length=2000)), migrations.AlterField(model_name='queuedsong', name='internal_url', field=models.CharField(... |
def propose_interpreters(spec, cache_dir, env):
existing = list(discover_pythons())
existing.sort(key=(lambda i: (*tuple((((- 1) if (j is None) else j) for j in i[1:4])), (1 if (i[0] == 'PythonCore') else 0))), reverse=True)
for (name, major, minor, arch, exe, _) in existing:
implementation = _IMPLE... |
class Effect11400(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('High Speed Maneuvering')), 'signatureRadiusBonus', ship.getModifiedItemAttr('shipBonusNavyDestroyerMinmatar3'), skill='Minmatar D... |
class MolGraph():
def __init__(self, mol: Union[(str, Chem.Mol)], atom_descriptors: np.ndarray=None):
if (type(mol) == str):
mol = Chem.MolFromSmiles(mol)
self.n_atoms = 0
self.n_bonds = 0
self.f_atoms = []
self.f_bonds = []
self.a2b = []
self.b2a ... |
(Nomination)
class NominationAdmin(admin.ModelAdmin):
raw_id_fields = ('nominee', 'nominator')
list_display = ('__str__', 'election', 'accepted', 'approved', 'nominee')
list_filter = ('election', 'accepted', 'approved')
def get_ordering(self, request):
return ['election', Lower('nominee__user__l... |
def get_edge_candidates(o: object) -> Iterator[tuple[(object, object)]]:
if ('__getattribute__' in getattr(type(o), '__dict__')):
return
if (type(o) not in COLLECTION_TYPE_BLACKLIST):
for attr in dir(o):
try:
if ((attr not in ATTR_BLACKLIST) and hasattr(o, attr) and (... |
def load_model(args, do_print=True):
colbert = ColBERT.from_pretrained('bert-base-uncased', query_maxlen=args.query_maxlen, doc_maxlen=args.doc_maxlen, dim=args.dim, similarity_metric=args.similarity, mask_punctuation=args.mask_punctuation)
colbert = colbert.to(DEVICE)
print_message('#> Loading model checkp... |
.parametrize('times, duration, expected_message', [[0, 0, 'times must be between 1 and 9'], [(- 1), 0, 'times must be between 1 and 9'], [10, 0, 'times must be between 1 and 9'], [11, 0, 'times must be between 1 and 9'], [3, 0, 'duration must be between 1 and 9'], [3, (- 1), 'duration must be between 1 and 9'], [3, 10,... |
class ButtonTestCases(unittest.TestCase):
def setUp(self):
_set_timings_fast()
self.app = Application()
self.app = self.app.start(os.path.join(mfc_samples_folder, u'CmnCtrl1.exe'))
self.app.Common_Controls_Sample.TabControl.select('CDateTimeCtrl')
self.ctrl = self.app.Common_... |
class AlwaysOnTopWindow(QtWidgets.QMainWindow):
def __init__(self, *args, m=None, **kwargs):
super().__init__(*args, **kwargs)
self.out_alpha = 0.25
self.m = m
self.app = QtWidgets.QApplication([]).instance()
self.setAttribute(Qt.WA_ShowWithoutActivating)
self.setWind... |
.parametrize('client_sends', [True, False])
.parametrize('code, reason', [(CloseReason.NORMAL_CLOSURE, 'bye'), (CloseReason.GOING_AWAY, '')])
def test_closure(client_sends: bool, code: CloseReason, reason: str) -> None:
client = Connection(CLIENT)
server = Connection(SERVER)
if client_sends:
local =... |
def create_repo():
def _create_repo(orgname, reponame, user):
r = create_repository(orgname, reponame, user)
assert (r is not None)
repo_ref = registry_model.lookup_repository(orgname, reponame)
assert (repo_ref is not None)
return repo_ref
return _create_repo |
class Term(with_metaclass(ABCMeta, object)):
dtype = NotSpecified
missing_value = NotSpecified
params = ()
domain = GENERIC
window_safe = False
ndim = 2
_term_cache = WeakValueDictionary()
def __new__(cls, domain=NotSpecified, dtype=NotSpecified, missing_value=NotSpecified, window_safe=N... |
def make_batches(lines, cfg, task, max_positions, encode_fn):
def encode_fn_target(x):
return encode_fn(x)
if cfg.generation.constraints:
batch_constraints = [list() for _ in lines]
for (i, line) in enumerate(lines):
if ('\t' in line):
(lines[i], *batch_constr... |
def test_create_legacy_tasks(db, settings):
Task.objects.all().delete()
xml_file = ((((Path(settings.BASE_DIR) / 'xml') / 'elements') / 'legacy') / 'tasks.xml')
root = read_xml_file(xml_file)
version = root.attrib.get('version')
elements = flat_xml_to_elements(root)
elements = convert_elements(e... |
_canonicalize
_rewriter([true_div, int_div])
def local_div_switch_sink(fgraph, node):
if ((node.op != true_div) and (node.op != int_div)):
return False
op = node.op
if (node.inputs[0].owner and (node.inputs[0].owner.op == switch)):
switch_node = node.inputs[0].owner
try:
... |
def get_dataset_videoswin(args, split='train', dataset_type=None):
from models.videoswintransformer_models.video_dataset import Video_SwinDataset
if (split == 'train'):
raise NotImplementedError('Training dataset processing for Video Swin Transformer to be added!')
elif (split == 'val'):
if ... |
def make_client(namespace: str, endpoint: config.EndpointConfiguration, log_if_unconfigured: bool, swallow_network_errors: bool=False) -> Client:
transport: Transport
if endpoint:
transport = RawTransport(endpoint, swallow_network_errors=swallow_network_errors)
else:
transport = NullTranspor... |
def summary(model, input_size, batch_size=(- 1), device='cuda'):
def register_hook(module):
def hook(module, input, output):
class_name = str(module.__class__).split('.')[(- 1)].split("'")[0]
module_idx = len(summary)
m_key = ('%s-%i' % (class_name, (module_idx + 1)))
... |
class OTTQA(datasets.GeneratorBasedBuilder):
def _info(self):
return datasets.DatasetInfo(description=_DESCRIPTION, features=datasets.Features({'id': datasets.Value('string'), 'question': datasets.Value('string'), 'table_id': datasets.Value('string'), 'table': {'header': datasets.features.Sequence(datasets.... |
def load_rl_model(discrete_act, pretrained_dir=None):
arg_model = 'tsdf-camrest'
arg_mode = 'interact'
cfg.init_handler(arg_model)
cfg.dataset = arg_model.split('-')[(- 1)]
logging.info(str(cfg))
if cfg.cuda:
torch.cuda.set_device(cfg.cuda_device)
logging.info('Device: {}'.format... |
def rmse(depth1, depth2):
assert np.all((((np.isfinite(depth1) & np.isfinite(depth2)) & (depth1 >= 0)) & (depth2 >= 0)))
diff = (depth1 - depth2)
num_pixels = float(diff.size)
if (num_pixels == 0):
return np.nan
else:
return np.sqrt((np.sum(np.square(diff)) / num_pixels)) |
class DDPTest(ComponentTestCase):
def test_ddp(self) -> None:
import torchx.components.dist as dist
self.validate(dist, 'ddp')
def test_ddp_mounts(self) -> None:
app = ddp(script='foo.py', mounts=['type=bind', 'src=/dst', 'dst=/dst', 'readonly'])
self.assertEqual(len(app.roles[0]... |
def run_legate(args):
import cunumeric as num
from legate.core import get_legate_runtime
from legate_kvikio.zarr import read_array
def f():
get_legate_runtime().issue_execution_fence(block=True)
t0 = clock()
a = read_array((args.dir / 'A'))
b = read_array((args.dir / 'B')... |
def main(args):
model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
if args.params:
keyname = 'params'
else:
keyname = 'params_ema'
model.load_state_dict(torch.load(args.input)[keyname])
model.train(False)
model.cpu().eval()
x = torc... |
class UsmmCscDense(_NoPythonCOp):
__props__ = ('inplace',)
def __init__(self, inplace):
self.inplace = inplace
if inplace:
self.destroy_map = {0: [6]}
def __str__(self):
if self.inplace:
return 'UsmmCscDense{inplace}'
else:
return 'UsmmCscD... |
def compute_mask_indices(shape: Tuple[(int, int)], padding_mask: Optional[torch.Tensor], mask_prob: float, mask_length: int, mask_type: str='static', mask_other: float=0.0, min_masks: int=0, no_overlap: bool=False, min_space: int=0) -> np.ndarray:
(bsz, all_sz) = shape
mask = np.full((bsz, all_sz), False)
a... |
def get_decode_dir_name(ckpt_name):
if ('train' in FLAGS.data_path):
dataset = 'train'
elif ('val' in FLAGS.data_path):
dataset = 'val'
elif ('test' in FLAGS.data_path):
dataset = 'test'
else:
raise ValueError(('FLAGS.data_path %s should contain one of train, val or test'... |
def generate_output_file_seg():
contexts = []
num = 0
with open(input_file, 'r', encoding='utf-8') as rf:
for line in rf:
line = line.strip()
if (line and ((num % interval) == 0)):
contexts.append(line.split('\t')[1:(- 1)])
num += 1
print(num)
... |
class CloseMatch(Token):
def __init__(self, match_string, maxMismatches=1):
super().__init__()
self.name = match_string
self.match_string = match_string
self.maxMismatches = maxMismatches
self.errmsg = ('Expected %r (with up to %d mismatches)' % (self.match_string, self.maxMi... |
class Effect2794(BaseEffect):
type = 'passive'
def handler(fit, container, context, projectionRange, **kwargs):
fit.modules.filteredItemIncrease((lambda mod: mod.item.requiresSkill('Salvaging')), 'accessDifficultyBonus', container.getModifiedItemAttr('accessDifficultyBonus'), position='post', **kwargs) |
class F18_PartData(F17_PartData):
removedKeywords = F17_PartData.removedKeywords
removedAttrs = F17_PartData.removedAttrs
def __init__(self, *args, **kwargs):
F17_PartData.__init__(self, *args, **kwargs)
self.hibernation = kwargs.get('hibernation', False)
self.cipher = kwargs.get('ci... |
def compute_global_div_n(caps, n=1):
aggr_div = []
all_ngrams = set()
lenT = 0.0
for k in caps:
for c in caps[k]:
tkns = c.split()
lenT += len(tkns)
ng = find_ngrams(tkns, n)
all_ngrams.update(ng)
if (n == 1):
aggr_div.append(float(len(... |
def update_config(config):
parser = argparse.ArgumentParser()
for setting in config.keys():
if ((type(config[setting]) == list) or (type(config[setting]) == type(None))):
parser.add_argument(('--' + setting), nargs='+')
else:
parser.add_argument(('--' + setting))
args... |
.skip
.slow
.parametrize('alg', learn_args.keys())
def test_mnist(alg):
learn_kwargs = learn_args[alg]
learn_kwargs.update(common_kwargs)
learn = get_learn_function(alg)
learn_fn = (lambda e: learn(env=e, **learn_kwargs))
env_fn = (lambda : MnistEnv(seed=0, episode_len=100))
simple_test(env_fn, ... |
class Hook():
def __init__(self, callback: Callable, user_data: Any=None, begin: int=1, end: int=0):
self.callback = callback
self.user_data = user_data
self.begin = begin
self.end = end
def bound_check(self, pc: int, size: int=1) -> bool:
return ((self.end < self.begin) ... |
def profile_tf_runningmeanstd():
import time
from baselines.common import tf_util
tf_util.get_session(config=tf.ConfigProto(inter_op_parallelism_threads=1, intra_op_parallelism_threads=1, allow_soft_placement=True))
x = np.random.random((376,))
n_trials = 10000
rms = RunningMeanStd()
tfrms =... |
def add_summarizer_args(parser):
parser.add_argument('--summarizer', type=str, default='gpt3_summarizer', choices=SUMMARIZER_CHOICES, help='model architecture')
parser.add_argument('--summarizer-save-dir', type=str, default=None, help='directory to save summarizer')
parser.add_argument('--summarizer-load-di... |
def calculate_class_properties(graph: Graph, scc: list[str], errors: Errors) -> None:
builtins = graph['builtins'].tree
assert builtins
for module in scc:
state = graph[module]
tree = state.tree
assert tree
for (_, node, _) in tree.local_definitions():
if isinstan... |
.xfail(reason='new_column_names is deprecated.')
def test_new_column_names(process_test_df):
result = process_test_df.process_text(column_name='text', new_column_names='new_text', string_function='slice', start=2)
expected = process_test_df.assign(new_text=process_test_df['text'].str.slice(start=2))
assert_... |
def parse_coredumpctl_line(line):
fields = {'time': (0, 28, str), 'pid': (29, 35, int), 'uid': (36, 41, int), 'gid': (42, 47, int), 'sig': (48, 51, int), 'present': (52, 53, _convert_present), 'exe': (54, None, str)}
data = {}
for (name, (start, end, converter)) in fields.items():
data[name] = conve... |
class CmdLock(ObjManipCommand):
key = 'lock'
aliases = ['locks']
locks = 'cmd: perm(locks) or perm(Builder)'
help_category = 'Building'
def func(self):
caller = self.caller
if (not self.args):
string = 'Usage: lock <object>[ = <lockstring>] or lock[/switch] <object>/<acce... |
def get_ansible_host(config: configparser.ConfigParser, inventory: Inventory, host: str, ssh_config: Optional[str]=None, ssh_identity_file: Optional[str]=None) -> Optional[testinfra.host.Host]:
if is_empty_inventory(inventory):
if (host == 'localhost'):
return testinfra.get_host('local://')
... |
def test_basetransformerlayer():
attn_cfgs = (dict(type='MultiheadAttention', embed_dims=256, num_heads=8),)
feedforward_channels = 2048
ffn_dropout = 0.1
operation_order = ('self_attn', 'norm', 'ffn', 'norm')
baselayer = BaseTransformerLayer(attn_cfgs=attn_cfgs, feedforward_channels=feedforward_cha... |
def spatial_svd_auto_mode():
sess = tf.compat.v1.Session()
with sess.graph.as_default():
_ = VGG16(weights=None, input_shape=(224, 224, 3))
init = tf.compat.v1.global_variables_initializer()
sess.run(init)
conv2d = sess.graph.get_operation_by_name('block1_conv1/Conv2D')
modules_to_ig... |
class FakeInspector(inspector.AbstractWebInspector):
def __init__(self, inspector_widget: QWidget, splitter: miscwidgets.InspectorSplitter, win_id: int, parent: QWidget=None) -> None:
super().__init__(splitter, win_id, parent)
self._set_widget(inspector_widget)
self._inspected_page = None
... |
def SolcoreMaterialToStr(material_input):
material_string = material_input.__str__().strip('<>').split(' ')
material_name = material_string[0].strip("'")
composition = {'material': material_name}
alloy = (True if (len(material_input.composition) > 0) else False)
if alloy:
material_compositio... |
class HierarchicalMultiHeadAttention(nn.Module):
def __init__(self, h, d_model, attn_p=0.1):
super(HierarchicalMultiHeadAttention, self).__init__()
self.h = h
self.d = d_model
assert ((d_model % h) == 0)
self.d_head = (d_model // h)
self.fc_query = Bottle(Linear(d_mod... |
class PatchSampler(object):
def __init__(self):
self.full_indices = None
def __call__(self, *args, **kwargs):
raise NotImplementedError
def image2patch(self, imgs, wh, device):
nbatch = imgs.shape[0]
(patch_coord, scale) = self(nbatch, wh, device)
if (not self.full_in... |
class QlFsMappedObject():
def __init__(self):
pass
def read(self, expected_len):
raise NotImplementedError('QlFsMappedObject method not implemented: read')
def write(self, buffer):
raise NotImplementedError('QlFsMappedObject method not implemented: write')
def fileno(self):
... |
.skipif((not HAVE_DEPS_FOR_RESOURCE_ESTIMATES), reason='pyscf and/or jax not installed.')
def test_lambda_calc():
mf = make_diamond_113_szv()
mymp = mp.KMP2(mf)
Luv = cholesky_from_df_ints(mymp)
helper = DFABKpointIntegrals(cholesky_factor=Luv, kmf=mf)
helper.double_factorize(thresh=1e-13)
hcore... |
def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern, error):
match = Search(pattern, line)
if (not match):
return False
sizeof_match = Match('.*sizeof\\s*$', line[0:(match.start(1) - 1)])
if sizeof_match:
return False
if (line[0:(match.start(1) - 1)].endswith(' ... |
class Laser():
DATA_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data')
DEFAULT_BPE_CODES_FILE = os.path.join(DATA_DIR, '93langs.fcodes')
DEFAULT_BPE_VOCAB_FILE = os.path.join(DATA_DIR, '93langs.fvocab')
DEFAULT_ENCODER_FILE = os.path.join(DATA_DIR, 'bilstm.93langs.2018-12-26.pt')
... |
def run_dijkstra_algorithm(start_node, nodes) -> None:
queue = PriorityQueue()
start_node.distance = 0
current_node = None
shortest_path = [start_node]
queue.put(PriorityItem(0, start_node))
while (not queue.empty()):
current_node = queue.get().item
for (node, weight) in current_... |
class InlineQueryResultCachedAudio(InlineQueryResult):
__slots__ = ('reply_markup', 'caption_entities', 'caption', 'parse_mode', 'audio_file_id', 'input_message_content')
def __init__(self, id: str, audio_file_id: str, caption: Optional[str]=None, reply_markup: Optional[InlineKeyboardMarkup]=None, input_message... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.