code stringlengths 281 23.7M |
|---|
class PackagesDistributionsEggTest(fixtures.EggInfoPkg, fixtures.EggInfoPkgPipInstalledNoToplevel, fixtures.EggInfoPkgPipInstalledNoModules, fixtures.EggInfoPkgSourcesFallback, unittest.TestCase):
def test_packages_distributions_on_eggs(self):
distributions = packages_distributions()
def import_name... |
class RedButton(DefaultObject):
def at_object_creation(self):
desc = 'This is a large red button, inviting yet evil-looking. '
desc += 'A closed glass lid protects it.'
self.db.desc = desc
self.db.lid_open = False
self.db.lamp_works = True
self.db.lid_locked = False
... |
def setUpModule():
global mol, mf
mol = gto.M()
mol.atom = 'O 0. 0. 0.\n H 0. -1. 2.\n H 0. 1. 2.'
mol.unit = 'Bohr'
mol.basis = 'sto3g'
mol.verbose = 4
mol.output = '/dev/null'
mol.build()
mf = dft.RKS(mol)
mf.chkfile = tempfile.NamedTemporaryFi... |
class SEResNet(nn.Module):
def __init__(self, block, layers, strides=(2, 2, 2, 2), dilations=(1, 1, 2, 4), zero_init_residual=True):
super(SEResNet, self).__init__()
self.inplanes = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = FixedBatch... |
class LagPrec():
def __init__(self, Adiag=None, level_shift=None, **kwargs):
self.Adiag = Adiag
self.level_shift = level_shift
def __call__(self, x):
Adiagd = (self.Adiag + self.level_shift)
Adiagd[(abs(Adiagd) < 1e-08)] = 1e-08
x /= Adiagd
return x |
class ConvBlock(nn.Module):
def __init__(self):
super(ConvBlock, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.c... |
class SmartlineV1(Instrument):
def __init__(self, adapter, name='Thyracont Vacuum Gauge V1', address=1, baud_rate=9600, **kwargs):
super().__init__(adapter, name, includeSCPI=False, write_termination='\r', read_termination='\r', asrl=dict(baud_rate=baud_rate), **kwargs)
self.address = address
de... |
def test_log_in_runtest_logreport(pytester: Pytester) -> None:
log_file = str(pytester.path.joinpath('pytest.log'))
pytester.makeini('\n [pytest]\n log_file={}\n log_file_level = INFO\n log_cli=true\n '.format(log_file))
pytester.makeconftest('\n import logging\n ... |
class TestEmbDimBucketer(unittest.TestCase):
def setUp(self) -> None:
super().setUp()
def gen_tables(self) -> Tuple[(List[ShardedEmbeddingTable], int)]:
num_tables = 103
num_buckets = 11
embeddings: List[ShardedEmbeddingTable] = []
buckets = random.sample(range(1024), num... |
def main():
rgb_image_filename = sys.argv[1]
left_template_filename = sys.argv[2]
right_template_filename = sys.argv[3]
image_path = sys.argv[4]
img_rgb = cv2.imread(rgb_image_filename)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread(left_template_filename, 0)
... |
def args():
parser = argparse.ArgumentParser(description='Test keypoints network')
parser.add_argument('--cfg', help='experiment configure file name', required=True, default='config.yaml', type=str)
parser.add_argument('--exp_name', help='experiment name', default='test', type=str)
parser.add_argument('... |
def remove_all_but_the_largest_connected_component(image: np.ndarray, for_which_classes: list, volume_per_voxel: float, minimum_valid_object_size: dict=None):
if (for_which_classes is None):
for_which_classes = np.unique(image)
for_which_classes = for_which_classes[(for_which_classes > 0)]
asser... |
def test_mixed_markers4(item_names_for):
test_content = '\n import pytest\n\n .order(2)\n def test_1():\n pass\n\n .order(index=1, after="test_3")\n def test_2():\n pass\n\n def test_3():\n pass\n '
assert (item_names_for(test_con... |
_hook('torchscript')
class TorchscriptHook(ClassyHook):
on_phase_start = ClassyHook._noop
on_phase_end = ClassyHook._noop
on_step = ClassyHook._noop
def __init__(self, torchscript_folder: str, use_trace: bool=True, trace_strict: bool=True, device: str='cpu') -> None:
super().__init__()
a... |
def compute_lambda(hcore: npt.NDArray, sparse_int_obj: SparseFactorization) -> SparseHamiltonianProperties:
kpts = sparse_int_obj.kmf.kpts
nkpts = len(kpts)
one_body_mat = np.empty(len(kpts), dtype=object)
lambda_one_body = 0.0
import time
for kidx in range(len(kpts)):
h1_pos = np.zeros_... |
def test_valid_organization(app):
someorg = model.user.get_namespace_user('buynlarge')
someorg.uuid = str(uuid.uuid4())
someorg.verified = True
someorg.save()
login_user(LoginWrappedDBUser(someorg.uuid, someorg))
result = validate_session_cookie()
assert (result.authed_user is None)
asse... |
def get_cone_chart(paths_data_frame, series_list, names_list, title=None, log_sacle=True):
line_chart = LineChart(log_scale=log_sacle)
for series_name in paths_data_frame:
series_element = DataElementDecorator(paths_data_frame[series_name], linewidth=1)
line_chart.add_decorator(series_element)
... |
class TestFunction():
def test_getmodulecollector(self, pytester: Pytester) -> None:
item = pytester.getitem('def test_func(): pass')
modcol = item.getparent(pytest.Module)
assert isinstance(modcol, pytest.Module)
assert hasattr(modcol.obj, 'test_func')
.filterwarnings('default')... |
def test_matplotlib_completions(config, workspace):
doc_mpl = 'import matplotlib.pyplot as plt; plt.'
com_position = {'line': 0, 'character': len(doc_mpl)}
doc = Document(DOC_URI, workspace, doc_mpl)
items = pylsp_jedi_completions(config, doc, com_position)
assert items
assert any((('plot' in i[... |
()
def main():
project_root = (Path(__file__).parent / '..')
os.chdir(project_root)
if git_repo_has_changes():
print('Your git repo has uncommitted changes. Commit or stash before continuing.')
sys.exit(1)
previous_branch = shell('git rev-parse --abbrev-ref HEAD', check=True, capture_out... |
def get_metadata_value(property_name):
setup_py_dir = os.path.join(os.path.dirname(__file__), '..', '..')
setup_py_file = os.path.join(setup_py_dir, 'setup.py')
out = subprocess.run(['python', setup_py_file, '-q', ('--%s' % property_name)], stdout=subprocess.PIPE, cwd=setup_py_dir, check=True)
property_... |
class MLP(nn.Module):
def __init__(self, in_features=2048, hidden_layers=[], activation='relu', bn=True, dropout=0.0):
super().__init__()
if isinstance(hidden_layers, int):
hidden_layers = [hidden_layers]
assert (len(hidden_layers) > 0)
self.out_features = hidden_layers[(... |
(HAS_SELF_TYPE)
def test_self_type():
class WithSelf():
a: int
next: Optional[typing.Self] = None
dumped_data = {'a': 1, 'next': None}
loaded_data = WithSelf(a=1)
assert (retort.dump(loaded_data) == dumped_data)
assert (retort.load(dumped_data, WithSelf) == loaded_data)
dumped_da... |
def main():
args = parse_args()
source_weights = torch.load(args.source_model)['model']
converted_weights = {}
keys = list(source_weights.keys())
prefix = 'backbone.bottom_up.'
for key in keys:
converted_weights[(prefix + key)] = source_weights[key]
torch.save(converted_weights, args... |
def statusCheck(probecheck=False):
status = ''
pprint(('Checking this system (%s)...' % platform.node()))
res = sysvals.colorText('NO (No features of this tool will work!)')
if sysvals.rootCheck(False):
res = 'YES'
pprint((' have root access: %s' % res))
if (res != 'YES'):
ppr... |
class TestDNSCache(unittest.TestCase):
def test_order(self):
record1 = r.DNSAddress('a', const._TYPE_SOA, const._CLASS_IN, 1, b'a')
record2 = r.DNSAddress('a', const._TYPE_SOA, const._CLASS_IN, 1, b'b')
cache = r.DNSCache()
cache.async_add_records([record1, record2])
entry = ... |
class TestPlotSummaryVariables(TestCase):
def test_plot(self):
model = pybamm.lithium_ion.SPM({'SEI': 'ec reaction limited'})
parameter_values = pybamm.ParameterValues('Mohtat2020')
experiment = pybamm.Experiment(([('Discharge at C/10 for 10 hours or until 3.3 V', 'Rest for 1 hour', 'Charge ... |
def parseEtree(inFileName, silence=False, print_warnings=True, mapping=None, reverse_mapping=None, nsmap=None):
parser = None
doc = parsexml_(inFileName, parser)
gds_collector = GdsCollector_()
rootNode = doc.getroot()
(rootTag, rootClass) = get_root_tag(rootNode)
if (rootClass is None):
... |
class Rect():
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def __repr__(self):
return ('Rect(%d, %d to %d, %d)' % (self.x1, self.y1, self.x2, self.y2))
def intersects(self, other):
return ((self.x2 > other.x1) and (se... |
def gdboutput(pipe):
global gdb_process
global gdb_lastresult
global gdb_lastline
global gdb_last_console_line
global gdb_stack_frame
global gdb_run_status
global gdb_stack_index
command_result_regex = re.compile('^\\d+\\^')
run_status_regex = re.compile('(^\\d*\\*)([^,]+)')
whil... |
class BertForMaskedLM(BertPreTrainedModel):
def __init__(self, config, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
self.bert = BertModel(config, add_pooling_layer=False)
self.cls = BertOnlyMLMHead(config)
self.post_init()
def forward(self, input_ids: Optional[... |
class TrainingConfig(FairseqDataclass):
common: CommonParams = CommonParams()
distributed_training: DistributedTrainingParams = DistributedTrainingParams()
dataset: DatasetParams = DatasetParams()
optimization: OptimizationParams = OptimizationParams()
checkpoint: CheckpointParams = CheckpointParams... |
class S3StoragePlugin(StoragePlugin):
def __init__(self, root: str, storage_options: Optional[Dict[(str, Any)]]=None) -> None:
try:
from aiobotocore.session import get_session
except ImportError:
raise RuntimeError('S3 support requires aiobotocore. Please make sure aiobotocor... |
def test_explicit_path(temp_dir, helpers):
config = {'path': f'foo/{DEFAULT_BUILD_SCRIPT}'}
file_path = ((temp_dir / 'foo') / DEFAULT_BUILD_SCRIPT)
file_path.ensure_parent_dir_exists()
file_path.write_text(helpers.dedent('\n from hatchling.metadata.plugin.interface import MetadataHookInterfac... |
class ActivateAccount(DeferredAction):
__tablename__ = 'activateaccount'
__mapper_args__ = {'polymorphic_identity': 'activateaccount'}
id = Column(Integer, ForeignKey(DeferredAction.id, ondelete='CASCADE'), primary_key=True)
system_account_id = Column(Integer, ForeignKey('systemaccount.id'), index=True)... |
class SuperResModel(UNetModel):
def __init__(self, in_channels, *args, **kwargs):
super().__init__((in_channels * 2), *args, **kwargs)
def forward(self, x, timesteps, low_res=None, **kwargs):
(_, _, new_height, new_width) = x.shape
upsampled = F.interpolate(low_res, (new_height, new_widt... |
def train(G_loss, D_loss, G_vars, D_vars, global_step):
G_optim = tf.train.AdamOptimizer(FLAGS.learning_rate, beta1=FLAGS.beta1)
D_optim = tf.train.AdamOptimizer(FLAGS.learning_rate, beta1=FLAGS.beta1)
G_grads = G_optim.compute_gradients(G_loss, var_list=G_vars)
D_grads = D_optim.compute_gradients(D_los... |
def test_select_column_using_expression_with_table_qualifier_without_column_alias():
sql = 'INSERT INTO tab1\nSELECT a.col1 + a.col2 + a.col3 + a.col4\nFROM tab2 a'
assert_column_lineage_equal(sql, [(ColumnQualifierTuple('col1', 'tab2'), ColumnQualifierTuple('a.col1 + a.col2 + a.col3 + a.col4', 'tab1')), (Colum... |
def validate_app_oauth_token(token):
validated = model.oauth.validate_access_token(token)
if (not validated):
logger.warning('OAuth access token could not be validated: %s', token)
return ValidateResult(AuthKind.oauth, error_message='OAuth access token could not be validated')
if (validated.... |
class MCHEvictionPolicy(abc.ABC):
def __init__(self, metadata_info: List[MCHEvictionPolicyMetadataInfo], threshold_filtering_func: Optional[Callable[([torch.Tensor], Tuple[(torch.Tensor, Union[(float, torch.Tensor)])])]]=None) -> None:
self._metadata_info = metadata_info
self._threshold_filtering_fu... |
(scope='module')
def input_text_message_content():
return InputTextMessageContent(TestInputTextMessageContentBase.message_text, parse_mode=TestInputTextMessageContentBase.parse_mode, entities=TestInputTextMessageContentBase.entities, disable_web_page_preview=TestInputTextMessageContentBase.disable_web_page_preview) |
class NAG(Optimizer):
def __init__(self, params, lr=required, momentum=0, weight_decay=0):
defaults = dict(lr=lr, lr_old=lr, momentum=momentum, weight_decay=weight_decay)
super(NAG, self).__init__(params, defaults)
def supports_memory_efficient_fp16(self):
return True
def supports_fl... |
class Effect5521(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
damageTypes = ('em', 'explosive', 'kinetic', 'thermal')
for damageType in damageTypes:
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Heavy Missiles')), ... |
class _DeformConv(Function):
def forward(ctx, input, offset, weight, stride=1, padding=0, dilation=1, groups=1, deformable_groups=1, im2col_step=64):
if ((input is not None) and (input.dim() != 4)):
raise ValueError('Expected 4D tensor as input, got {}D tensor instead.'.format(input.dim()))
... |
class VerifyHandler(BaseHandler):
async def get(self, code):
userid = None
try:
async with self.db.transaction() as sql_session:
verified_code = base64.b64decode(code)
(userid, verified_code) = (await self.db.user.decrypt(0, verified_code, sql_session=sql_... |
def select_components(components, exclude_components=None):
short_component_names = [shorten_component_name(name) for name in REPO_LIST_ALL]
output = set([])
for component in components:
if (component == 'ALL'):
for repo in REPO_LIST_ALL:
output.add(repo)
elif (co... |
class SpeechTransformerEncoder(TransformerEncoder):
def __init__(self, opt, dicts, positional_encoder, encoder_type='text', language_embeddings=None):
self.death_rate = opt.death_rate
self.learnable_position_encoding = opt.learnable_position_encoding
self.layer_modules = list()
self.... |
.usefixtures('session_app_data')
def test_session_report_subprocess(tmp_path):
out = check_output([sys.executable, '-m', 'virtualenv', str(tmp_path), '--activators', 'powershell', '--without-pip'], text=True, encoding='utf-8')
lines = out.split('\n')
regexes = ['created virtual environment .* in \\d+ms', ' ... |
def get_packages(root_dir='aitom', exclude_dir_roots=['aitom/tomominer/core/src', 'aitom/tomominer/core/cython']):
pkg = []
for (root, dirs, files) in os.walk(root_dir):
exclude = False
for d in exclude_dir_roots:
if root.startswith(d):
exclude = True
if exclu... |
def run_step(context):
logger.debug('started')
context.assert_key_has_value('fileWriteYaml', __name__)
input_context = context.get_formatted('fileWriteYaml')
assert_key_has_value(obj=input_context, key='path', caller=__name__, parent='fileWriteYaml')
out_path = Path(input_context['path'])
payloa... |
def test_resnet():
with pytest.raises(KeyError):
ResNet(20)
with pytest.raises(AssertionError):
ResNet(50, num_stages=0)
with pytest.raises(AssertionError):
ResNet(50, num_stages=5)
with pytest.raises(AssertionError):
ResNet(50, strides=(1,), dilations=(1, 1), num_stages=... |
def pytest_addoption(parser: Parser) -> None:
group = parser.getgroup('terminal reporting')
group.addoption('--junitxml', '--junit-xml', action='store', dest='xmlpath', metavar='path', type=functools.partial(filename_arg, optname='--junitxml'), default=None, help='Create junit-xml style report file at given pat... |
class ProcessWrapper():
def __init__(self, pathscript=None):
logger.debug('Initializing %s: (pathscript: %s)', self.__class__.__name__, pathscript)
self.tk_vars = get_config().tk_vars
self.set_callbacks()
self.pathscript = pathscript
self.command = None
self.statusbar... |
def binary_op(name: str, arg_types: list[RType], return_type: RType, c_function_name: str, error_kind: int, var_arg_type: (RType | None)=None, truncated_type: (RType | None)=None, ordering: (list[int] | None)=None, extra_int_constants: (list[tuple[(int, RType)]] | None)=None, steals: StealsDescription=False, is_borrowe... |
class _FileStreamCloser(_StreamCloser, _FileCloser):
def __init__(self, write, close_on_exit, is_binary, temp_file, chunk_size, delete_failures):
_StreamCloser.__init__(self, write, close_on_exit)
_FileCloser.__init__(self, temp_file, delete_failures)
self.is_binary = is_binary
self.... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-mode')
parser.add_argument('-model')
parser.add_argument('-cfg', nargs='*')
args = parser.parse_args()
cfg.init_handler(args.model)
cfg.dataset = args.model.split('-')[(- 1)]
if args.cfg:
for pair in args.cfg:
... |
def test_qat():
if (version.parse(tf.version.VERSION) >= version.parse('2.00')):
model = dense_functional()
rand_inp = np.random.randn(10, 5)
rand_out = np.random.randn(10, 2)
qsim = QuantizationSimModel(model, quant_scheme='tf', default_param_bw=8, default_output_bw=8)
qsim.... |
def check_package_data(dist, attr, value):
if (not isinstance(value, dict)):
raise DistutilsSetupError('{!r} must be a dictionary mapping package names to lists of string wildcard patterns'.format(attr))
for (k, v) in value.items():
if (not isinstance(k, str)):
raise DistutilsSetupEr... |
class Migration(migrations.Migration):
dependencies = [('sponsors', '0097_sponsorship_renewal')]
operations = [migrations.AlterField(model_name='sponsorship', name='renewal', field=models.BooleanField(blank=True, help_text='If true, it means the sponsorship is a renewal of a previous sponsorship and will use th... |
def check_link_path(link: Link) -> int:
if os.path.isabs(link.uri):
fullname = link.uri
else:
dirname = os.path.dirname(link.file)
fullname = os.path.join(dirname, link.uri)
if os.path.exists(fullname):
ok(link)
return 0
else:
fail(link, ('NoFile ' + fulln... |
class Effect7077(BaseEffect):
type = 'passive'
def handler(fit, module, context, projectionRange, **kwargs):
fit.modules.filteredItemMultiply((lambda mod: (mod.item.group.name == 'Precursor Weapon')), 'damageMultiplier', module.getModifiedItemAttr('damageMultiplier'), stackingPenalties=True, **kwargs) |
class PreactivatedBottleneckTransformation(nn.Module):
def __init__(self, dim_in, dim_out, temporal_stride, spatial_stride, num_groups, dim_inner, temporal_kernel_size=3, temporal_conv_1x1=True, spatial_stride_1x1=False, inplace_relu=True, bn_eps=1e-05, bn_mmt=0.1, disable_pre_activation=False, **kwargs):
s... |
def test_requirement_source_fix_explicit_subdep_resolver_error(req_file):
source = _init_requirement([(req_file(), 'flask==2.0.1')])
flask_deps = source.collect()
jinja_dep: (ResolvedDependency | None) = None
for dep in flask_deps:
if (isinstance(dep, ResolvedDependency) and (dep.canonical_name ... |
def test_connection_request() -> None:
event = _make_connection_request([(b'Host', b'localhost'), (b'Connection', b'Keep-Alive, Upgrade'), (b'Upgrade', b'websocket'), (b'Sec-WebSocket-Version', b'13'), (b'Sec-WebSocket-Key', generate_nonce()), (b'X-Foo', b'bar')])
assert (event.extensions == [])
assert (eve... |
def set_subfolders_for_roots_JIF(root, radiometry_depth):
if (radiometry_depth == 8):
return {'lr': os.path.join(root, 'lr_dataset', '*', 'L2A', ''), 'lrc': os.path.join(root, 'lr_dataset', '*', 'L2A', ''), 'hr': os.path.join(root, 'hr_dataset', '8bit', '*', ''), 'hr_pan': os.path.join(root, 'hr_dataset', '... |
class AnsiCmd(object):
def __init__(self, forceAnsi):
self.forceAnsi = forceAnsi
def cmdReset(self):
if (sys.stdout.isatty() or self.forceAnsi):
return (ESC + '[0m')
else:
return ''
def cmdColour(self, colour):
if (sys.stdout.isatty() or self.forceAnsi... |
class TestRequired(TestNameCheckVisitorBase):
_passes()
def test_typing_extensions(self):
from typing_extensions import NotRequired, Required, TypedDict
class RNR(TypedDict):
a: int
b: Required[str]
c: NotRequired[float]
def take_rnr(td: RNR) -> None:
... |
def parse_id666(data):
tags = {}
tags['title'] = data[:32]
tags['album'] = data[32:64]
tags['dumper'] = data[64:80]
tags['comments'] = data[80:112]
if (data[130:(130 + 1)] < b'A'):
try:
tags['~#length'] = int(data[123:126].strip(b'\x00'))
except ValueError:
... |
def test_exporter_can_export_requirements_txt_with_directory_packages_and_markers(tmp_path: Path, poetry: Poetry, fixture_root_uri: str) -> None:
poetry.locker.mock_lock_data({'package': [{'name': 'foo', 'version': '1.2.3', 'optional': False, 'python-versions': '*', 'marker': "python_version < '3.7'", 'source': {'t... |
def _get_rw_sharding_perf(batch_sizes: List[int], world_size: int, local_world_size: int, input_lengths: List[float], emb_dim: int, input_data_type_size: float, table_data_type_size: float, fwd_a2a_comm_data_type_size: float, bwd_a2a_comm_data_type_size: float, fwd_sr_comm_data_type_size: float, bwd_sr_comm_data_type_s... |
def _ListBoxTruncInfo(win):
lineFormat = (win32defines.DT_SINGLELINE | win32defines.DT_NOPREFIX)
truncData = []
for title in win.texts():
newRect = win.client_rects()[0]
newRect.right -= 2
newRect.bottom -= 1
truncData.append((title, newRect, win.font(), lineFormat))
retu... |
def chunked(iterable, n, strict=False):
iterator = iter(partial(take, n, iter(iterable)), [])
if strict:
if (n is None):
raise ValueError('n must not be None when using strict mode.')
def ret():
for chunk in iterator:
if (len(chunk) != n):
... |
def test_nested_sequence():
class WrappedIntent(object):
effect = attr.ib()
value = attr.ib()
def internal():
(yield Effect(1))
(yield Effect(2))
return 'wrap'
def code_under_test():
r = (yield Effect(WrappedIntent(internal(), 'field')))
r2 = (yield Ef... |
def parseContent(openId, MsgContent):
openId = openId.lower()
try:
list_content = MsgContent.replace(',', ' ').replace(',', ' ').replace('.', ' ').replace(':', ' ').replace('', '1').replace('', '2').replace('', '').strip().split()
if ((len(list_content) < 1) or (list_content[0] not in LST_INSTR)... |
def retrieve_available_artifacts():
class Artifact():
def __init__(self, name: str):
self.name = name
self.paths = []
def __str__(self):
return self.name
def add_path(self, path: str):
self.paths.append({'name': self.name, 'path': path})
_a... |
def test_no_rerun_on_strict_xfail_with_only_rerun_flag(testdir):
testdir.makepyfile('\n import pytest\n .xfail(strict=True)\n def test_xfail():\n assert True\n ')
result = testdir.runpytest('--reruns', '1', '--only-rerun', 'RuntimeError')
assert_outcomes(result, passed=0, ... |
class CoffeeMakerMode(IntEnum):
_UNKNOWN = _UNKNOWN
REFILL = 0
Refill = 0
PLACE_CARAFE = 1
PlaceCarafe = 1
REFILL_WATER = 2
RefillWater = 2
READY = 3
Ready = 3
BREWING = 4
Brewing = 4
BREWED = 5
Brewed = 5
CLEANING_BREWING = 6
CleaningBrewing = 6
CLEANING_... |
def test_vertical_perspective_operation():
aeaop = VerticalPerspectiveConversion(viewpoint_height=10, latitude_topocentric_origin=1, longitude_topocentric_origin=2, false_easting=3, false_northing=4, ellipsoidal_height_topocentric_origin=5)
assert (aeaop.name == 'unknown')
assert (aeaop.method_name == 'Vert... |
class MemCOW(COW):
def __init__(self, addr, imagefd, logger, seek_lock):
self.addr = addr
self.imagefd = imagefd
self.seek_lock = seek_lock
self.logger = helpers.get_child_logger(logger, 'FS')
self.logger.info('Copy-On-Write for {0} in Memory'.format(addr))
self.fh = ... |
()
_context
('--add', '-a', help='Name of api key to add')
('--list', '-l', is_flag=True, help='List all API keys')
('--super', '-s', is_flag=True, help="API Key has super user priviledges (has access to other application's data)")
def key(ctx, add, list, super):
try:
keys = APIKey.query.all()
if (a... |
class CmdConfigureTest(unittest.TestCase):
def setUp(self) -> None:
self.parser = argparse.ArgumentParser()
self.cmd_configure = CmdConfigure()
self.cmd_configure.add_arguments(self.parser)
self.test_dir = tempfile.mkdtemp(prefix='torchx_cmd_configure_test')
self._old_cwd = o... |
class OptimizationTest(unittest.TestCase):
def assertListAlmostEqual(self, list1, list2, tol):
self.assertEqual(len(list1), len(list2))
for (a, b) in zip(list1, list2):
self.assertAlmostEqual(a, b, delta=tol)
def test_adam_w(self):
w = torch.tensor([0.1, (- 0.2), (- 0.1)], re... |
.skipif((platform.system() != 'Linux'), reason='test requires /proc/self/ mechanism')
def test_open_file_usage_never_exceeds_1000(runner, monkeypatch, tmp_path):
schema_path = (tmp_path / 'schema.json')
schema_path.write_text('{}')
args = ['--schemafile', str(schema_path)]
for i in range(2000):
... |
class DevNetTS(BaseDeepAD):
def __init__(self, epochs=100, batch_size=64, lr=0.001, network='Transformer', seq_len=100, stride=1, rep_dim=128, hidden_dims='100,50', act='ReLU', bias=False, n_heads=8, d_model=512, attn='self_attn', pos_encoding='fixed', norm='LayerNorm', margin=5.0, l=5000, epoch_steps=(- 1), prt_st... |
.end_to_end()
def test_collect_produces_that_is_not_str_or_path(tmp_path, capsys):
source = '\n import pytask\n\n .produces(True)\n def task_with_non_path_dependency():\n pass\n '
tmp_path.joinpath('task_module.py').write_text(textwrap.dedent(source))
session = build(paths=tmp_path)
a... |
def test_nested_process_search_dv_over_100_terms(s1_product: SentinelOne):
list_o_terms = list(range(1, 106))
first_list = (('("' + '", "'.join([str(x) for x in list(range(1, 101))])) + '")')
second_list = (('("' + '", "'.join([str(x) for x in list(range(101, 106))])) + '")')
s1_product._queries = {}
... |
class SumDiffOp(Op):
def make_node(self, x, y):
x = pt.as_tensor_variable(x)
y = pt.as_tensor_variable(y)
outdim = x.type.ndim
output1 = TensorType(dtype=pytensor.scalar.upcast(x.dtype, y.dtype), shape=((None,) * outdim))()
output2 = TensorType(dtype=pytensor.scalar.upcast(x.... |
class encoder(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0):
super().__init__()
dim_0 = 2
dim_2 = 64
dim_3 = 128
dim_4 = 256
dim_5 = 512
self.fc1 = nn.Linear(dim_0, dim_2)
self.fc3 = n... |
class SecuredMethod(BoundFunctionWrapper):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _self_read_check(self, *args, **kwargs):
return self._self_parent.check_right(self.read_check, self._self_instance, *args, **kwargs)
def _self_write_check(self, *args, **kwar... |
.end_to_end()
def test_collect_task_with_ignore_from_config(runner, tmp_path):
source = '\n import pytask\n\n .depends_on("in_1.txt")\n .produces("out_1.txt")\n def task_example_1():\n pass\n '
tmp_path.joinpath('task_example_1.py').write_text(textwrap.dedent(source))
source = '\n .... |
class DoubleSubVector(_DoubleVectorBase, _matrix_ext.DoubleSubVector):
def __init__(self, obj, start=0, length=None):
if (not isinstance(obj, _kaldi_vector.DoubleVectorBase)):
obj = numpy.array(obj, dtype=numpy.float64, copy=False, order='C')
if (obj.ndim != 1):
raise... |
def preprocess_triplet_data(samples: List[Tuple[(EntityContext, EntityContext, EntityContext)]], tokenizer: PreTrainedTokenizer, max_seq_length=64, disable_tqdm=False):
raw_sentences = []
for sample in samples:
(ent_ctx_a, ent_ctx_b, ent_ctx_c) = sample
raw_sentences.extend([ent_ctx_a.left_conte... |
def get_labels(sample, context_mode):
(user_labels, agent_labels) = ([], [])
for qa in sample['QA']:
user_labels.extend(qa['QueSummUttIDs'])
agent_labels.extend(qa['AnsSummLongUttIDs'])
if (context_mode == 'both'):
b_user_labels = binary_label(list(set(user_labels)), len(sample['Dial... |
def test_parse_summary_line_always_plural() -> None:
lines = ['some output 1', 'some output 2', '======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s ====', 'done.']
assert (pytester_mod.RunResult.parse_summary_nouns(lines) == {'errors': 1, 'failed': 1, 'passed': 1, 'warnings': 1})
lines = ['some output ... |
.parametrize('output, version', [(MUSL_AMD64, _MuslVersion(1, 2)), (MUSL_I386, _MuslVersion(1, 2)), (MUSL_AARCH64, _MuslVersion(1, 1)), (MUSL_INVALID, None), (MUSL_UNKNOWN, None)], ids=['amd64-1.2.2', 'i386-1.2.1', 'aarch64-1.1.24', 'invalid', 'unknown'])
def test_parse_musl_version(output, version):
assert (_parse... |
.parametrize('text, deleted, rest', [pytest.param('test foobar| delete', ' delete', 'test foobar|', marks=fixme), ('test foobar| delete', ' ', 'test foobar|delete'), pytest.param('test foo|delete bar', 'delete', 'test foo| bar', marks=fixme), ('test foo|delete bar', 'delete ', 'test foo|bar'), pytest.param('test foo<ba... |
class SelectiveKernel(nn.Module):
def __init__(self, in_channels, out_channels=None, kernel_size=None, stride=1, dilation=1, groups=1, rd_ratio=(1.0 / 16), rd_channels=None, rd_divisor=8, keep_3x3=True, split_input=True, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d, aa_layer=None, drop_layer=None):
super(Se... |
class AttentiveConvNet(Classifier):
def __init__(self, dataset, config):
super(AttentiveConvNet, self).__init__(dataset, config)
self.attentive_conv_net_type = config.AttentiveConvNet.type
self.attention_type = config.AttentiveConvNet.attention_type
self.dim = config.embedding.dimens... |
class PPOMoleculeGenerator():
def __init__(self, model: SmilesRnnActorCritic, max_seq_length, device) -> None:
self.model = model
self.max_seq_length = max_seq_length
self.device = device
self.sampler = SmilesRnnSampler(device=device, batch_size=512)
def optimise(self, objective:... |
def fully_connected(shape, inputs, num_outputs, scope, use_xavier=True, stddev=0.001, weight_decay=0.0, activation_fn=tf.nn.relu, bn=False, bn_decay=None, is_training=None):
with tf.variable_scope(scope) as sc:
num_input_units = shape[(- 1)]
weights = _variable_with_weight_decay('weights', shape=[nu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.