code stringlengths 281 23.7M |
|---|
def _extra_requirement_for_node(game: GameDescription, context: NodeContext, node: Node) -> (Requirement | None):
extra_requirement = None
if node.is_resource_node:
assert isinstance(node, ResourceNode)
dangerous_extra = [ResourceRequirement.simple(resource) for (resource, quantity) in node.reso... |
def test_cli_explicit_format(input_file):
fmt = input_file.suffix.lstrip('.')
with input_file.open() as fp, mock.patch('pathlib.Path.open', return_value=fp), mock.patch('builtins.print') as print_:
main(['-f', fmt, 'no-file.invalid'])
print_.assert_called_once()
((result,), _) = print_.c... |
def context_feature_extractor(graph, hop_num, num_relation):
start = time()
context_df = context_extractor(g=graph, hop_num=hop_num)
context_df = feature_extractor(context_df=context_df, graph=graph, num_relation=num_relation)
print('Graph node feature extraction takes {:.2f} seconds'.format((time() - s... |
class Effect6093(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
for damageType in ('em', 'explosive', 'kinetic', 'thermal'):
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Heavy Missiles')), '{0}Damage'.format(damageType), sh... |
class TimeLimitedBatch(Batch):
def __init__(self, inner: Batch, max_age: float):
self.batch = inner
self.batch_start: Optional[float] = None
self.max_age = max_age
def age(self) -> float:
if (not self.batch_start):
return 0
return (time.time() - self.batch_sta... |
class Effect7031(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Heavy Missiles')), 'kineticDamage', src.getModifiedItemAttr('shipBonusCBC2'), skill='Caldari Battlecruiser', **kwargs) |
def load_model_from_config(config, ckpt, verbose=False):
print(f'Loading model from {ckpt}')
pl_sd = torch.load(ckpt, map_location='cpu')
if ('global_step' in pl_sd):
print(f"Global Step: {pl_sd['global_step']}")
sd = pl_sd['state_dict']
model = instantiate_from_config(config.model)
(m, ... |
def measure_inference_speed(cfg, checkpoint, max_iter, log_interval, is_fuse_conv_bn, use_fp16):
if cfg.get('cudnn_benchmark', False):
torch.backends.cudnn.benchmark = True
cfg.model.pretrained = None
cfg.data.test.test_mode = True
samples_per_gpu = cfg.data.test.pop('samples_per_gpu', 1)
if... |
(autouse=True)
def check_gc(request):
if ('test_ipython' in request.node.name):
(yield)
return
try:
from qtpy import API_NAME
except Exception:
API_NAME = ''
marks = set((mark.name for mark in request.node.iter_markers()))
if ('allow_bad_gc' in marks):
(yield)... |
def get_completion(prompt, model='text-davinci-003', max_tokens=100):
response = openai.Completion.create(engine=model, prompt=prompt, max_tokens=max_tokens, n=1, stop='\n\n', temperature=1, top_p=1, logprobs=1)
return (response.choices[0].logprobs['tokens'], response.choices[0].logprobs['token_logprobs']) |
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
(self.b_size, self.n_mines) = LEVELS[1]
w = QWidget()
hb = QHBoxLayout()
self.mines = QLabel()
self.mines.setAlignment((Qt.AlignHCenter | Qt.AlignVCen... |
()
('file', type=click.File(mode='r'))
('--extra-mod-name', '-e', multiple=True, help='Name of imported module to also check')
('--no-decorate-main', is_flag=True, default=True, help='Disable decorating FILE')
def check_contracts(file: TextIO, extra_mod_name: Tuple, no_decorate_main: bool):
contents = file.read()
... |
_lr_scheduler('reduce_lr_on_plateau')
class ReduceLROnPlateau(FairseqLRScheduler):
def __init__(self, args, optimizer):
super().__init__(args, optimizer)
if (len(args.lr) > 1):
raise ValueError('Cannot use a fixed learning rate schedule with reduce_lr_on_plateau. Consider --lr-scheduler=... |
class Effect4023(BaseEffect):
runTime = 'early'
type = ('projected', 'passive')
def handler(fit, beacon, context, projectionRange, **kwargs):
fit.modules.filteredChargeMultiply((lambda mod: mod.charge.requiresSkill('Missile Launcher Operation')), 'aoeVelocity', beacon.getModifiedItemAttr('aoeVelocit... |
class TrainableFidelityStatevectorKernel(TrainableKernel, FidelityStatevectorKernel):
def __init__(self, *, feature_map: (QuantumCircuit | None)=None, statevector_type: Type[SV]=Statevector, training_parameters: ((ParameterVector | Sequence[Parameter]) | None)=None, cache_size: (int | None)=None, auto_clear_cache: ... |
def main():
pp.connect(use_gui=True)
pp.add_data_path()
p.resetDebugVisualizerCamera(cameraDistance=2, cameraPitch=(- 20), cameraYaw=80, cameraTargetPosition=[0, 0, 0])
plane = p.loadURDF('plane.urdf')
ri = reorientbot.pybullet.PandaRobotInterface()
box = pp.create_box(0.7, 0.1, 0.4)
p.reset... |
def open3d_to_trimesh(src):
if isinstance(src, open3d.geometry.TriangleMesh):
vertex_colors = None
if src.has_vertex_colors:
vertex_colors = np.asarray(src.vertex_colors)
dst = trimesh.Trimesh(vertices=np.asarray(src.vertices), faces=np.asarray(src.triangles), vertex_normals=np.a... |
class ConvertSegmentationToRegionsTransform(AbstractTransform):
def __init__(self, regions: Union[(List, Tuple)], seg_key: str='seg', output_key: str='seg', seg_channel: int=0):
self.seg_channel = seg_channel
self.output_key = output_key
self.seg_key = seg_key
self.regions = regions
... |
class FileReader(Reader, FileHandler):
mode = Option(str, default='r', __doc__='\n What mode to use for open() call.\n ')
output_fields = Option(ensure_tuple, required=False, __doc__='\n Specify the field names of output lines.\n Mutually exclusive with "output_type".\n ')
output_... |
_staging_test
class ConfigPushToHubTester(unittest.TestCase):
def setUpClass(cls):
cls._token = login(username=USER, password=PASS)
def tearDownClass(cls):
try:
delete_repo(token=cls._token, name='test-config')
except HTTPError:
pass
try:
delet... |
def init_batchdata():
print('reading word embedding data...')
vec = []
word2id = {}
f = open('./origin_data/vec.txt', encoding='utf-8')
info = f.readline()
print('word vec info:', info)
while True:
content = f.readline()
if (content == ''):
break
content =... |
def accuracy(pred, target, topk=1):
assert isinstance(topk, (int, tuple))
if isinstance(topk, int):
topk = (topk,)
return_single = True
else:
return_single = False
res = []
mask = (target >= 0)
for k in topk:
(_, idx) = pred.topk(k, dim=1)
pred_label = tor... |
class SE_Res2Block(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation, scale, se_bottleneck_dim):
super().__init__()
self.Conv1dReluBn1 = Conv1dReluBn(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
self.Res2Conv1dReluBn = Res2Conv... |
def set_handler(args):
old_value = get_client_parameter(args.hostname, args.parameter)
try:
old = set_client_parameter(args.hostname, args.parameter, args.value)
except Exception as e:
sys.exit('Failed to set parameter: {}'.format(e))
if (not old_value):
with logbook.StreamHandle... |
class FairseqEncoder(nn.Module):
def __init__(self, dictionary):
super().__init__()
self.dictionary = dictionary
def forward(self, src_tokens, src_lengths=None, **kwargs):
raise NotImplementedError
def reorder_encoder_out(self, encoder_out, new_order):
raise NotImplementedErr... |
_cache(maxsize=None)
def has_working_ipv6():
if (not socket.has_ipv6):
return False
sock = None
try:
sock = socket.socket(socket.AF_INET6)
sock.bind(('::1', 0))
except Exception:
return False
finally:
if sock:
sock.close()
for iface in ifaddr.g... |
class PID_DATA(object):
def __init__(self, n_question, seqlen, separate_char, maxstep, name='data'):
self.separate_char = separate_char
self.n_question = n_question
self.seqlen = seqlen
self.maxstep = maxstep
def load_data(self, path):
f_data = open(path, 'r')
ski... |
class MetaCIFAR100(CIFAR100):
def __init__(self, args, partition='train', train_transform=None, test_transform=None, fix_seed=True):
super(MetaCIFAR100, self).__init__(args, partition, False)
self.fix_seed = fix_seed
self.n_ways = args.n_ways
self.n_shots = args.n_shots
self.... |
class LazyBinaryReadFile(click.File):
def convert(self, value: ((str | os.PathLike[str]) | t.IO[t.Any]), param: (click.Parameter | None), ctx: (click.Context | None)) -> t.IO[bytes]:
if (hasattr(value, 'read') or hasattr(value, 'write')):
return t.cast(t.IO[bytes], value)
value_: (str | ... |
class TestToDict(object):
def setup_method(self):
self.testInst = pysat.Instrument('pysat', 'testing', num_samples=5, use_header=True)
self.stime = pysat.instruments.pysat_testing._test_dates['']['']
self.testInst.load(date=self.stime)
self.out = None
return
def teardown_... |
def build_optimizer(optimizer_cfg: Union[(DictConfig, Namespace)], params, *extra_args, **extra_kwargs):
if all((isinstance(p, dict) for p in params)):
params = [t for p in params for t in p.values()]
params = list(filter((lambda p: p.requires_grad), params))
return _build_optimizer(optimizer_cfg, p... |
class HardwareClientBase():
handler = None
def __init__(self, *, plugin: 'HW_PluginBase'):
assert_runs_in_hwd_thread()
self.plugin = plugin
def device_manager(self) -> 'DeviceMgr':
return self.plugin.device_manager()
def is_pairable(self) -> bool:
raise NotImplementedErro... |
class DuckGame():
def __init__(self, rows: int=4, columns: int=3, minimum_solutions: int=1):
self.rows = rows
self.columns = columns
size = (rows * columns)
self._solutions = None
self.claimed_answers = {}
self.scores = defaultdict(int)
self.editing_embed = as... |
def test_symbolic_lusolve_full_mass_matrix():
sys = models.n_link_pendulum_on_cart(n=5, cart_force=False, joint_torques=False)
g_symbolic_solve = CythonODEFunctionGenerator(sys.eom_method.forcing_full, sys.coordinates, sys.speeds, sys.constants_symbols, mass_matrix=sys.eom_method.mass_matrix_full, linear_sys_so... |
class TestDailyBarData(WithCreateBarData, WithBarDataChecks, WithDataPortal, ZiplineTestCase):
START_DATE = pd.Timestamp('2016-01-05', tz='UTC')
END_DATE = ASSET_FINDER_EQUITY_END_DATE = pd.Timestamp('2016-01-11', tz='UTC')
CREATE_BARDATA_DATA_FREQUENCY = 'daily'
ASSET_FINDER_EQUITY_SIDS = set(range(1, ... |
def recover_data(steg_image_path: str, output_file_path: str, num_lsb: int) -> None:
if (steg_image_path is None):
raise ValueError('LSBSteg recovery requires an input image file path')
if (output_file_path is None):
raise ValueError('LSBSteg recovery requires an output file path')
(steg_ima... |
def test_rd_As_wr_At_impl_disjoint():
class Top(ComponentLevel3):
def construct(s):
s.A = Wire(Bits32)
def up_wr_At():
s.A[16:32] = Bits16(255)
def up_rd_As():
assert (s.A[0:16] == 0)
m = Top()
m.elaborate()
simple_sim_pass(m, 2... |
class MaskFormerConfig(PretrainedConfig):
model_type = 'maskformer'
attribute_map = {'hidden_size': 'mask_feature_size'}
backbones_supported = ['resnet', 'swin']
decoders_supported = ['detr']
def __init__(self, fpn_feature_size: int=256, mask_feature_size: int=256, no_object_weight: float=0.1, use_a... |
class DistMaster(CovController):
_ensure_topdir
def start(self):
cleanup()
if (self.cov_config and os.path.exists(self.cov_config)):
if hasattr(self.config.option, 'rsyncdir'):
self.config.option.rsyncdir.append(self.cov_config)
self.cov = coverage.Coverage(so... |
class ExportMixin():
def export_as_csv(self, request, queryset):
import csv
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="exported_data.csv"'
writer = csv.writer(response)
writer.writerow(['Proposal Info', 'Author In... |
def make_from_route_from_counter(counter):
from_channel = factories.create(factories.NettingChannelStateProperties(canonical_identifier=factories.make_canonical_identifier(), token_address=factories.make_token_address(), partner_state=factories.NettingChannelEndStateProperties(balance=next(counter), address=factori... |
def _call_new_layers_sequentially(parent_layers: List[tf.keras.layers.Layer], new_layers: List[tf.keras.layers.Layer]) -> tf.Tensor:
curr_tensor = []
for parent_layer in parent_layers:
curr_tensor.append(parent_layer.output)
if (len(curr_tensor) == 1):
curr_tensor = curr_tensor[0]
for la... |
class CT_RelationshipBuilder(BaseBuilder):
def __init__(self):
self._rId = 'rId9'
self._reltype = 'ReLtYpE'
self._target = 'docProps/core.xml'
self._target_mode = None
self._indent = 0
self._namespace = (' xmlns="%s"' % NS.OPC_RELATIONSHIPS)
def with_rId(self, rId... |
class TestOmitted(RoundTripMixin, unittest.TestCase):
def setUp(self):
self.enum = 'blank'
self.missing_terms = [None, float('nan')]
def test_roundtrip_all_missing_float(self):
expected = ([None, float('nan')] + self.missing_terms)
series = pd.Series(expected, dtype=float)
... |
class LongformerTokenizerFast(PreTrainedTokenizerFast):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
model_input_names = ['input_ids', 'attention_mask']
slow_tokenizer_class = LongformerTo... |
def test_log_warning_stats_knows_SamplerWarning(caplog):
warn = convergence.SamplerWarning(convergence.WarningType.BAD_ENERGY, 'Not that interesting', 'debug')
stats = [dict(warning=warn)]
with caplog.at_level(logging.DEBUG, logger='pymc'):
convergence.log_warning_stats(stats)
assert ('Not that ... |
def test_unify_Op():
op1 = CustomOp(1)
op2 = CustomOp(1)
s = unify(op1, op2)
assert (s == {})
s = unify(etuplize(op1), op2)
assert (s == {})
op1_np = CustomOpNoProps(1)
op2_np = CustomOpNoProps(1)
s = unify(op1_np, op2_np)
assert (s == {})
op1_np_neq = CustomOpNoPropsNoEq(1)
... |
_REGISTRY.register()
def build_resnet_fpn_backbone(cfg, input_shape: ShapeSpec):
bottom_up = build_resnet_backbone(cfg, input_shape)
in_features = cfg.MODEL.FPN.IN_FEATURES
out_channels = cfg.MODEL.FPN.OUT_CHANNELS
backbone = FPN(bottom_up=bottom_up, in_features=in_features, out_channels=out_channels, n... |
_config
def test_move_floating(manager):
manager.test_window('one')
assert (manager.c.window.info()['width'] == 798)
assert (manager.c.window.info()['height'] == 578)
assert (manager.c.window.info()['x'] == 0)
assert (manager.c.window.info()['y'] == 0)
manager.c.window.toggle_floating()
asse... |
.mpl_image_compare(baseline_dir='output/oo')
def test_filled_with_colormap_contours_calm_limit():
ax = WindroseAxes.from_ax()
ax.contourf(wd, ws, bins=bins, cmap=cm.hot, calm_limit=0.2)
ax.contour(wd, ws, bins=bins, colors='black', calm_limit=0.2)
ax.set_legend()
return ax.figure |
def train(model, dataloader, optimizer, criterion, epoch_number, max_gradient_norm):
model.train()
device = model.device
epoch_start = time.time()
batch_time_avg = 0.0
running_loss = 0.0
preds = []
golds = []
for (batch_index, batch) in enumerate(dataloader):
batch_start = time.t... |
(frozen=True)
class FileAttachment():
filename: str
content: bytes
def __repr__(self) -> str:
content = (f'{self.content[:10]}...' if (len(self.content) > 10) else self.content)
return f'FileAttachment(path={self.filename!r}, content={content})'
def suffix(self) -> str:
return Pu... |
_module()
class ToDataContainer(object):
def __init__(self, fields):
self.fields = fields
def __call__(self, results):
for field in self.fields:
_field = field.copy()
key = _field.pop('key')
results[key] = DC(results[key], **_field)
return results
... |
class Effect6535(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: (mod.item.requiresSkill('Skirmish Command') or mod.item.requiresSkill('Armored Command'))), 'warfareBuff3Value', src.getModifiedItemAttr('shipBonusForceAux... |
def debug_p(*args):
now_ts = time.time()
millisecond = str(str(now_ts).split('.')[(- 1)])[:3]
t = ((str(time.strftime('%Y.%m.%d_%H:%M:%S', time.localtime(now_ts))) + '.') + millisecond)
args = ' '.join([str(e) for e in args])
if DEBUG_MODEL:
print(((('----#' + t) + '|') + args)) |
def run(results_root: str, apps: List[shared.TestApp]):
with shared.todomvc_server() as server:
unexpected_result_tests = []
try:
shutil.rmtree(results_root, ignore_errors=True)
os.makedirs(results_root)
browsers: List[shared.Browser] = ['firefox']
for... |
def test_imdb():
random.seed(time.time())
if (random.random() > 0.8):
((x_train, y_train), (x_test, y_test)) = imdb.load_data()
((x_train, y_train), (x_test, y_test)) = imdb.load_data(maxlen=40)
assert (len(x_train) == len(y_train))
assert (len(x_test) == len(y_test))
wor... |
def test_conversions():
assert (pressure('30', 'in').value('in') == 30.0)
assert (abs((pressure('30', 'in').value('mb') - 1015.92)) < 0.01)
assert (abs((pressure('30', 'in').value('hPa') - 1015.92)) < 0.01)
assert pressure('30', 'in').string('in'), '30.00 inches'
assert pressure('30', 'in').string('... |
('pypyr.moduleloader.get_module')
(Step, 'invoke_step')
def test_run_pipeline_steps_complex_with_multistep_none_run(mock_invoke_step, mock_module):
steps = [{'name': 'step1', 'run': False}, {'name': 'step2', 'run': 0}, {'name': 'step3', 'run': None}]
context = get_test_context()
original_len = len(context)
... |
class OutPath(OwnedPath):
def _destruct(cls, path):
if (not os.path.exists(path)):
return
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.unlink(path)
def __new__(cls, dir=False, **kwargs):
if dir:
name = tempfile.mkdtemp(**kwa... |
class TestBeforeTradingStart(zf.WithMakeAlgo, zf.ZiplineTestCase):
START_DATE = pd.Timestamp('2016-01-06', tz='utc')
END_DATE = pd.Timestamp('2016-01-07', tz='utc')
SIM_PARAMS_CAPITAL_BASE = 10000
SIM_PARAMS_DATA_FREQUENCY = 'minute'
EQUITY_DAILY_BAR_LOOKBACK_DAYS = EQUITY_MINUTE_BAR_LOOKBACK_DAYS =... |
class GDBRegister():
def __init__(self, name, index, val):
self.name = name
self.index = index
self.value = val
self.line = 0
self.lines = 0
def format(self, line=0):
val = self.value
if (('{' not in val) and re.match('[\\da-yA-Fx]+', val)):
va... |
def test_byhand_awav2wav():
CRVAL3A = (6560 * u.AA).to(u.m).value
CDELT3A = (1.0 * u.AA).to(u.m).value
CUNIT3A = 'm'
CRPIX3A = 1.0
mywcs = wcs.WCS(naxis=1)
mywcs.wcs.ctype[0] = 'AWAV'
mywcs.wcs.crval[0] = CRVAL3A
mywcs.wcs.crpix[0] = CRPIX3A
mywcs.wcs.cunit[0] = CUNIT3A
mywcs.wcs... |
class MetricToolkitTest(unittest.TestCase):
def test_metric_sync(self) -> None:
num_processes = (torch.cuda.device_count() if torch.cuda.is_available() else 4)
input_tensor = torch.rand((num_processes * 2))
self._launch_metric_sync_test(num_processes, input_tensor, DummySumMetric)
se... |
def test_add_with_sub_dependencies(installer: Installer, locker: Locker, repo: Repository, package: ProjectPackage) -> None:
package_a = get_package('A', '1.0')
package_b = get_package('B', '1.1')
package_c = get_package('C', '1.2')
package_d = get_package('D', '1.3')
repo.add_package(package_a)
... |
def SaveMesh(mesh, project, path):
directory = Path(path).resolve().parent
directory.mkdir(parents=True, exist_ok=True)
with open(path, 'w+') as f:
i = 0
for vertex in mesh.verts:
i += 1
f.write((str(round(vertex.x, 8)) + '/'))
f.write((str(round(vertex.y,... |
class Effect6898(BaseEffect):
runTime = 'early'
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Remote Armor Repair Systems')), 'mediumRemoteRepFittingMultiplier', src.getModifiedItemAttr('subsystemMRARFit... |
class ProjectManager(PymiereBaseObject):
def __init__(self, pymiere_id=None):
super(ProjectManager, self).__init__(pymiere_id)
' The `ProjectManagerOptions` structure. '
def options(self):
kwargs = self._eval_on_this_object('options')
return (ProjectManagerOptions(**kwargs) if kwargs... |
_config
def test_tall_window_focus_cycle(manager):
manager.test_window('one')
manager.test_window('two')
manager.test_window('float1')
manager.c.window.toggle_floating()
manager.test_window('float2')
manager.c.window.toggle_floating()
manager.test_window('three')
assert (manager.c.layout... |
def transforms_imagenet_eval(img_size=224, crop_pct=None, interpolation='bilinear', use_prefetcher=False, mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD):
crop_pct = (crop_pct or DEFAULT_CROP_PCT)
if isinstance(img_size, tuple):
assert (len(img_size) == 2)
if (img_size[(- 1)] == img_size[(... |
class GLShaderLexer(RegexLexer):
name = 'GLSL'
aliases = ['glsl']
filenames = ['*.vert', '*.frag', '*.geo']
mimetypes = ['text/x-glslsrc']
url = '
version_added = '1.1'
tokens = {'root': [('#(?:.*\\\\\\n)*.*$', Comment.Preproc), ('//.*$', Comment.Single), ('/(\\\\\\n)?[*](.|\\n)*?[*](\\\\\\n... |
def repeat_eval_ckpt(model, test_loader, args, eval_output_dir, logger, ckpt_dir, dist_test=False):
ckpt_record_file = (eval_output_dir / ('eval_list_%s.txt' % cfg.DATA_CONFIG.DATA_SPLIT['test']))
with open(ckpt_record_file, 'a'):
pass
total_time = 0
first_eval = True
while True:
(cu... |
def create_door(options: DoorOptions):
from ...btools.building.arch import ArchProperty
from ...btools.building.array import ArrayProperty
from ...btools.building.sizeoffset import SizeOffsetProperty
register_property(ArchProperty)
register_property(ArrayProperty)
register_property(SizeOffsetPro... |
class ModleWithLoss(torch.nn.Module):
def __init__(self, model, loss):
super(ModleWithLoss, self).__init__()
self.model = model
self.loss = loss
def forward(self, batch):
pre_img = (batch['pre_img'] if ('pre_img' in batch) else None)
pre_hm = (batch['pre_hm'] if ('pre_hm'... |
class TestVonNeumannEntropy():
.parametrize('p', np.linspace(0, 1, 17))
def test_binary(self, p):
dm = qutip.qdiags([p, (1 - p)], 0)
expected = (0 if (p in [0, 1]) else ((p * np.log2(p)) + ((1 - p) * np.log2((1 - p)))))
assert (abs(((- qutip.entropy_vn(dm, 2)) - expected)) < 1e-12)
.... |
def _check_path_header(headers, hdr_validation_flags):
def inner():
for header in headers:
if (header[0] in (b':path', u':path')):
if (not header[1]):
raise ProtocolError('An empty :path header is forbidden')
(yield header)
skip_validation = (h... |
_test
def test_layer_call_arguments():
inp = layers.Input(shape=(2,))
x = layers.Dense(3)(inp)
x = layers.Dropout(0.5)(x, training=True)
model = Model(inp, x)
assert (not model.uses_learning_phase)
inp2 = layers.Input(shape=(2,))
out2 = model(inp2)
assert (not out2._uses_learning_phase)
... |
def test_chaining_priority():
layouts = make_layouts(TestField('a'), name_mapping(map={'a': 'x'}), name_mapping(map={'a': 'y'}), DEFAULT_NAME_MAPPING)
assert (layouts == Layouts(InputNameLayout(crown=InpDictCrown(map={'x': InpFieldCrown('a')}, extra_policy=ExtraSkip()), extra_move=None), OutputNameLayout(crown=... |
class NonBlockingMap(MapDataPipe):
not_available_hook = default_not_available_hook
def __getitem__(self, index):
while True:
try:
return self.nonblocking_getitem(index)
except NotAvailable:
if (NonBlockingMap.not_available_hook is not None):
... |
def get_role_information(generic_items: Iterable[Dict[(str, Any)]]) -> Dict[(str, Any)]:
roles = {}
GT_KEY = 'generictemplate'
METADATA_KEY = 'metadata'
LABEL_KEY = 'labels'
ROLE_KEY = 'torchx.pytorch.org/role-name'
SPEC_KEY = 'spec'
CONTAINER_KEY = 'containers'
IMAGE_KEY = 'image'
A... |
def train_model(config, model, train_path, test_path):
print('Training...')
model_path = get_model_path(config, model)
config_path = get_config_path(config, model)
vocab_path = get_vocab_path(config, model)
log_path = get_log_path(config, model)
if (os.path.exists(model_path) and os.path.exists(... |
class LVCNetGenerator(torch.nn.Module):
def __init__(self, in_channels=1, out_channels=1, inner_channels=8, cond_channels=80, cond_hop_length=256, lvc_block_nums=3, lvc_layers_each_block=10, lvc_kernel_size=3, kpnet_hidden_channels=64, kpnet_conv_size=1, dropout=0.0, use_weight_norm=True):
super().__init__(... |
def write_parametrized_method_test(file, test_name, cls_name, comm_pairs_list, args_list, kwargs_list, values_list, test, inkwargs=None):
z = zip(comm_pairs_list, args_list, kwargs_list, values_list)
params = [f''' ({cp},
{a}, {k}, {v}),
'''.replace('), (', '),\n (') for (cp, a, k, v) in z]
hea... |
class InvertibleConv1x1(nn.Module):
def __init__(self, num_channels, LU_decomposed=False):
super().__init__()
w_shape = [num_channels, num_channels]
w_init = np.linalg.qr(np.random.randn(*w_shape))[0].astype(np.float32)
if (not LU_decomposed):
self.register_parameter('wei... |
def masked_mse_torch(preds, labels, null_val=np.nan):
if np.isnan(null_val):
mask = (~ torch.isnan(labels))
else:
mask = torch.ne(labels, null_val)
mask = mask.to(torch.float32)
mask /= torch.mean(mask)
mask = torch.where(torch.isnan(mask), torch.zeros_like(mask), mask)
loss = to... |
class BlenderbotConfig(PretrainedConfig):
model_type = 'blenderbot'
keys_to_ignore_at_inference = ['past_key_values']
attribute_map = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}
def __init__(self, vocab_size=8008, max_position_embeddings=128, encoder_layers=2, encoder_ff... |
(PARTITION_TYPE='TRI')
def test_concept_style_cuts():
assert (list(compute.subsystem.concept_cuts(Direction.CAUSE, (0,))) == [KCut(Direction.CAUSE, KPartition(Part((), ()), Part((), (0,)), Part((0,), ())))])
assert (list(compute.subsystem.concept_cuts(Direction.EFFECT, (0,))) == [KCut(Direction.EFFECT, KPartiti... |
def process_text_truthfulqa_adv(text):
if ('I am sorry' in text):
first_period = text.index('.')
start_idx = (first_period + 2)
text = text[start_idx:]
if (('as an AI language model' in text) or ('As an AI language model' in text)):
first_period = text.index('.')
start_id... |
class Contact(TinyBaseModel):
schema = {'email': {'type': 'string'}, 'domain': {'type': 'string'}, 'firstname': {'type': 'string', 'maxlength': 55}, 'lastname': {'type': 'string', 'maxlength': 55}, 'emails_sent': {'type': 'integer'}, 'emails_received': {'type': 'integer'}}
def __init__(self, **kwargs):
... |
def read_csi(file: PathType, storage_options: Optional[Dict[(str, str)]]=None) -> CSIIndex:
with open_gzip(file, storage_options=storage_options) as f:
magic = read_bytes_as_value(f, '4s')
if (magic != b'CSI\x01'):
raise ValueError('File not in CSI format.')
(min_shift, depth, l_... |
class WheelArchive():
def __init__(self, project_id: str, *, reproducible: bool) -> None:
self.metadata_directory = f'{project_id}.dist-info'
self.shared_data_directory = f'{project_id}.data'
self.time_tuple: (TIME_TUPLE | None) = None
self.reproducible = reproducible
if self... |
.parametrize('status, body', [(409, ''), (400, 'File already exists'), (400, 'Repository does not allow updating assets'), (403, 'Not enough permissions to overwrite artifact'), (400, 'file name has already been taken')])
def test_uploader_skips_existing( type[ uploader: Uploader, status: int, body: str) -> None:
... |
def test_trim_matrix():
arr = np.full((100, 100), np.nan)
arr[((- 1), (- 1))] = 1.0
assert (util.trimMatrix(arr).shape == (1, 1))
arr[((- 2), (- 2))] = 1.0
assert (util.trimMatrix(arr).shape == (2, 2))
arr[np.diag_indices_from(arr)] = 1.0
assert (util.trimMatrix(arr).shape == arr.shape) |
def build_ranked_golds(dataset, docdb, ranker):
golds = build_gold_dict(dataset)
questions = build_questions_dict(dataset)
ranked_dict = {}
for (q_id, pars) in tqdm(golds.items()):
par1_score = ranker.get_similarity_with_doc(questions[q_id], pars[0])
par2_score = ranker.get_similarity_wi... |
def test_dependency_loop(item_names_for, capsys):
test_content = '\n import pytest\n\n .order(after="test_3")\n def test_1():\n pass\n\n .order(1)\n def test_2():\n pass\n\n .order(before="test_1")\n def test_3():\n pass\n '
... |
(lists(simple_typed_classes(frozen=True), min_size=1), sampled_from(([(tuple, Tuple), (tuple, tuple), (list, list), (list, List), (deque, Deque), (set, Set), (set, set), (frozenset, frozenset), (frozenset, FrozenSet), (list, MutableSequence), (deque, MutableSequence), (tuple, Sequence)] if is_py39_plus else [(tuple, Tu... |
.skipif((parse(torch.__version__) < parse('2.0')), reason='Avoid pickle error')
.skipif((sys.version_info.minor <= 7), reason='reduce test is incompatible with python 3.7 or lower (cannot pickle the op Enum).')
class TestReduce():
def client(memmap_filename, rank, op, async_op, return_premature):
os.environ... |
class TeamCompulsion(ScrimsButton):
def __init__(self, ctx: Context, letter: str):
super().__init__(emoji=ri(letter))
self.ctx = ctx
async def callback(self, interaction: Interaction):
(await interaction.response.defer())
self.view.record.teamname_compulsion = (not self.view.reco... |
_ansi_style(ansi.AllowStyle.ALWAYS)
def test_ansi_pouterr_always_tty(mocker, capsys):
app = AnsiApp()
mocker.patch.object(app.stdout, 'isatty', return_value=True)
mocker.patch.object(sys.stderr, 'isatty', return_value=True)
app.onecmd_plus_hooks('echo_error oopsie')
(out, err) = capsys.readouterr()
... |
class UserTableIOStats(QueryStats):
path = '%(datname)s.tables.%(schemaname)s.%(relname)s.%(metric)s'
multi_db = True
query = '\n SELECT relname,\n schemaname,\n heap_blks_read,\n heap_blks_hit,\n idx_blks_read,\n idx_blks_hit\n ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.