code stringlengths 281 23.7M |
|---|
class InlineQueryResultVoice(InlineQueryResult):
def __init__(self, voice_url: str, title: str, id: str=None, voice_duration: int=0, caption: str='', parse_mode: Optional['enums.ParseMode']=None, caption_entities: List['types.MessageEntity']=None, reply_markup: 'types.InlineKeyboardMarkup'=None, input_message_conte... |
.parametrize('input_username, expected_output', [('jake', 'jake'), ('frank', 'frank'), ('fra-nk', 'fra-nk'), ('Jake', 'jake'), ('FranK', 'frank'), ('ja__ke', 'ja_ke'), ('ja___ke', 'ja_ke'), ('ja__', 'ja'), ('jake__', 'jake'), ('_jake', 'jake'), ('a', 'a0'), ('ab', 'ab'), ('abc', 'abc'), ('abcdefghijklmnopqrstuvwxyz', '... |
def _create_and_upload_workflows(workflow: str, workflow_range: (int, int), file: Optional[str]=None, workers: int=WORKERS_DEFAULT_COUNT) -> None:
logger.info(f'Creating and uploading {workflow_range} workflows...')
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
futures = [... |
class Model(TrainableModel):
def __init__(self, embedding_size: int, lr: float, loss_fn: str, mining: str):
self._embedding_size = embedding_size
self._lr = lr
self._loss_fn = loss_fn
self._mining = mining
super().__init__()
def configure_encoders(self) -> Union[(Encoder,... |
class RemovedCommand(KickstartCommand):
def __init__(self, writePriority=None, *args, **kwargs):
if (self.__class__ is RemovedCommand):
raise TypeError('RemovedCommand is an abstract class.')
KickstartCommand.__init__(self, writePriority, *args, **kwargs)
def dataList(self):
... |
.parametrize(['func', 'kind'], [pytest.param((lambda t, A: (A - 4)), (lambda : qutip.MCSolver.ExpectFeedback(qutip.num(10))), id='expect'), pytest.param((lambda t, A: ((len(A) < 3) * 1.0)), (lambda : qutip.MCSolver.CollapseFeedback()), id='collapse')])
def test_feedback(func, kind):
tol = 1e-06
psi0 = qutip.bas... |
def _encode_object(obj):
is_nonbool_int = (isinstance(obj, int) and (not isinstance(obj, (bool, np.bool_))))
is_encode_type = isinstance(obj, (float, str, np.integer, np.floating))
if (is_nonbool_int or is_encode_type):
return obj
elif isinstance(obj, np.ndarray):
return _encode_numpy_ar... |
class TestCheckOverflow():
def test_good(self):
cmdutils.check_overflow(1, 'int')
def test_bad(self):
int32_max = ((2 ** 31) - 1)
with pytest.raises(cmdutils.CommandError, match='Numeric argument is too large for internal int representation.'):
cmdutils.check_overflow((int32_... |
class ViewProviderAsmElement(ViewProviderAsmOnTop):
_iconName = 'Assembly_Assembly_Element.svg'
_iconDisabledName = 'Assembly_Assembly_ElementDetached.svg'
def __init__(self, vobj):
vobj.addProperty('App::PropertyBool', 'ShowCS', '', 'Show coordinate cross')
vobj.ShapeColor = self.getDefault... |
class AutoUpdatePeekLayerDropdown(QtWidgets.QComboBox):
def __init__(self, *args, m=None, layers=None, exclude=None, use_active=False, empty_ok=True, **kwargs):
super().__init__(*args, **kwargs)
self.m = m
self._layers = layers
self._exclude = exclude
self._use_active = use_a... |
def test_jax_shape_ops():
x_np = np.zeros((20, 3))
x = Shape()(pt.as_tensor_variable(x_np))
x_fg = FunctionGraph([], [x])
compare_jax_and_py(x_fg, [], must_be_device_array=False)
x = Shape_i(1)(pt.as_tensor_variable(x_np))
x_fg = FunctionGraph([], [x])
compare_jax_and_py(x_fg, [], must_be_de... |
class FC(nn.Sequential):
def __init__(self, in_size: int, out_size: int, *, activation=nn.ReLU(inplace=True), bn: bool=False, init=None, preact: bool=False, name: str=''):
super().__init__()
fc = nn.Linear(in_size, out_size, bias=(not bn))
if (init is not None):
init(fc.weight)
... |
def test_maximum_builds(app):
user = model.user.create_user('foobar', 'password', '')
user.maximum_queued_builds_count = 1
user.save()
repo = model.repository.create_repository('foobar', 'somerepo', user)
prepared_build = PreparedBuild()
prepared_build.build_name = 'foo'
prepared_build.is_ma... |
def pq_compute_multi_core(matched_annotations_list, gt_folder, pred_folder, categories):
cpu_num = multiprocessing.cpu_count()
annotations_split = np.array_split(matched_annotations_list, cpu_num)
print('Number of cores: {}, images per core: {}'.format(cpu_num, len(annotations_split[0])))
workers = mult... |
class RemoveCmdPrefix(_QtileMigrator):
ID = 'RemoveCmdPrefix'
SUMMARY = 'Removes ``cmd_`` prefix from method calls and definitions.'
HELP = '\n The ``cmd_`` prefix was used to identify methods that should be exposed to\n qtile\'s command API. This has been deprecated and so calls no longer require\n ... |
class TestSerialLoopback():
ADAPTER_TIMEOUT = 1.0
()
def adapter(self, connected_device_address):
device = connected_device_address.split(',')[0]
return SerialAdapter(device, baudrate=19200, timeout=self.ADAPTER_TIMEOUT, read_termination=chr(15))
()
def loopback(self, connected_devic... |
def arguments_mock():
arguments = SimpleNamespace()
arguments.url = ''
arguments.dmenu_invocation = 'rofi -dmenu'
arguments.insert_mode = True
arguments.io_encoding = 'UTF-8'
arguments.merge_candidates = False
arguments.password_only = False
arguments.username_only = False
arguments.... |
def transform_for_stmt(builder: IRBuilder, s: ForStmt) -> None:
def body() -> None:
builder.accept(s.body)
def else_block() -> None:
assert (s.else_body is not None)
builder.accept(s.else_body)
for_loop_helper(builder, s.index, s.expr, body, (else_block if s.else_body else None), s.i... |
class CsObject():
__metaclass__ = ABCMeta
def __init__(self, objType):
self.objectType = objType
self.label = ''
self.deleted = 0
self.verified = 0
self.date = ''
self.user = ''
self.draw = True
def __str__(self):
pass
def fromJsonText(self... |
def get_env_info():
import torch
import torchvision
from basicsr.version import __version__
msg = '\n ____ _ _____ ____\n / __ ) ____ _ _____ (_)_____/ ___/ / __ \\\n / __ |/ __ `// ___// // ___/\\__ \\ / /_/ /\n / /_/ // /_/ /... |
def get_project_dependencies(project_requires: list[Dependency], locked_packages: list[Package], root_package_name: NormalizedName) -> Iterable[tuple[(Package, Dependency)]]:
packages_by_name: dict[(str, list[Package])] = {}
for pkg in locked_packages:
if (pkg.name not in packages_by_name):
... |
class SerializableOptimizer(Configurable):
def __init__(self, opt_name, params=None):
if ('learning_rate' not in params):
raise ValueError('Must include learning rate')
self.params = params
self.opt_name = opt_name
self.lr_op = None
def get_params(self):
retur... |
def test_to_pep_508_caret() -> None:
dependency = Dependency('foo', '^1.2.3')
assert (dependency.to_pep_508() == 'foo (>=1.2.3,<2.0.0)')
dependency = Dependency('foo', '^1.2')
assert (dependency.to_pep_508() == 'foo (>=1.2,<2.0)')
dependency = Dependency('foo', '^0.2.3')
assert (dependency.to_pe... |
def _get_labels_and_probs(y_pred: np.ndarray, task_type: TaskType, prediction_type: Optional[PredictionType]) -> tuple[(np.ndarray, Optional[np.ndarray])]:
assert (task_type in (TaskType.BINCLASS, TaskType.MULTICLASS))
if (prediction_type is None):
return (y_pred, None)
if (prediction_type == Predic... |
def test_vertical_perspective():
crs = ProjectedCRS(conversion=VerticalPerspectiveConversion(50, 0, 1, 0, 2, 3))
expected_cf = {'semi_major_axis': 6378137.0, 'semi_minor_axis': crs.ellipsoid.semi_minor_metre, 'inverse_flattening': crs.ellipsoid.inverse_flattening, 'reference_ellipsoid_name': 'WGS 84', 'longitud... |
def main():
parser = argparse.ArgumentParser('Dataset preprocessing')
parser.add_argument('dataset', choices=['cp_v2', 'v2', 'cp_v1'])
args = parser.parse_args()
if (args.dataset == 'v2'):
load_v2()
elif (args.dataset == 'cp_v1'):
load_cp_v1()
elif (args.dataset == 'cp_v2'):
... |
def find_closest_msssim(target, img, fmt='jpeg'):
lower = 0
upper = 100
prev_mid = upper
def _mssim(a, b):
a = torch.from_numpy(np.asarray(a).astype(np.float32)).permute(2, 0, 1).unsqueeze(0)
b = torch.from_numpy(np.asarray(b).astype(np.float32)).permute(2, 0, 1).unsqueeze(0)
ret... |
def train(args):
mode = args.mode
if (args.fusionType != 'C'):
if (args.mode != 'both'):
print("Only Concat fusion supports one stream versions. Changing mode to /'both/'...")
mode = 'both'
if (args.lstmType == '3dconvblock'):
raise Exception('3dconvblock inst... |
def make_labels(n=1000, n_classes=3, one_hot=False, seed=99999):
rstate = np.random.RandomState(seed)
def _one_hot(x):
(classes, x) = np.unique(x, return_inverse=True)
return np.column_stack([(x == c) for c in classes])
ref_labels = rstate.randint(n_classes, size=n)
sys_labels = rstate.r... |
def test_base_variables():
for file in ['t.py', 't.json', 't.yaml']:
cfg_file = osp.join(data_path, f'config/{file}')
cfg = Config.fromfile(cfg_file)
assert isinstance(cfg, Config)
assert (cfg.filename == cfg_file)
assert (cfg.item1 == [1, 2])
assert (cfg.item2.a == 0... |
.parametrize('username,password', users)
def test_update_m2m_multisite(db, client, username, password):
client.login(username=username, password=password)
instances = OptionSet.objects.all()
for instance in instances:
optionset_options = [{'option': optionset_option.option.id, 'order': optionset_opt... |
def parse_args():
parser = argparse.ArgumentParser(description='FCGEC Switch Module Params')
base_args = ArgumentGroup(parser, 'base', 'Base Settings')
base_args.add_arg('mode', str, 'train', 'Experiment Mode')
base_args.add_arg('cuda', bool, True, 'device : True - CUDA, False - CPU (Force)')
base_a... |
def init_model(args, device, n_gpu, local_rank):
if args.init_model:
model_state_dict = torch.load(args.init_model, map_location='cpu')
else:
model_state_dict = None
cache_dir = (args.cache_dir if args.cache_dir else os.path.join(str(PYTORCH_PRETRAINED_BERT_CACHE), 'distributed'))
model ... |
def test_dsl_async_cmd_serial_multiple_expanded_syntax_save():
echo = get_cmd('tests/testfiles/cmds/echo-out-and-err.sh', 'tests\\testfiles\\cmds\\echo-out-and-err.bat')
context = Context({'cmds': [{'run': [f'{echo} A', [f'{echo} B.1', f'{echo} B.2'], f'{echo} C'], 'save': True}, {'run': [[f'{echo} D.1', f'{ech... |
class PlaylistLibrary(Library[(str, Playlist)]):
def __init__(self, library: Library, pl_dir: _fsnative=_DEFAULT_PLAYLIST_DIR):
self.librarian = None
super().__init__(f'{type(self).__name__} for {library._name}')
print_d(f'Initializing Playlist Library {self} to watch {library._name!r}')
... |
.sphinx(srcdir=srcdir, confoverrides={'hoverxref_ignore_refs': ['section i']})
def test_ignore_refs(app, status, warning):
app.build()
path = (app.outdir / 'index.html')
assert (path.exists() is True)
content = open(path).read()
chunks = ['<a class="reference internal" href="chapter-i.html#chapter-i... |
def weights_init_kaiming(m):
classname = m.__class__.__name__
if ((classname.find('Conv') != (- 1)) or (classname.find('ConvTranspose') != (- 1))):
init.kaiming_normal_(m.weight.data, a=0, mode='fan_in', nonlinearity='relu')
if (m.bias is not None):
m.bias.data.zero_()
elif (clas... |
('randovania.games.prime2.patcher.claris_randomizer.validate_game_files_path', autospec=True)
('randovania.games.prime2.patcher.claris_randomizer.get_data_path', autospec=True)
def test_base_args(mock_get_data_path: MagicMock, mock_validate_game_files_path: MagicMock):
mock_get_data_path.return_value = Path('data')... |
class TestLoggingForTestGenerator():
message = b'some written message'
def adapter(self, caplog):
adapter = ProtocolAdapter()
caplog.set_level(logging.DEBUG)
return adapter
def test_write(self, adapter, caplog):
adapter.comm_pairs = [(self.message, None)]
written = se... |
def test_export_logs_failure(initialized_db):
test_storage.put_content('local_us', 'except_upload', b'true')
repo = model.repository.get_repository('devtable', 'simple')
user = model.user.get_user('devtable')
worker = ExportActionLogsWorker(None)
called = [{}]
(netloc='testcallback')
def han... |
class scoped_configure(object):
def __init__(self, dir=None, format_strs=None):
self.dir = dir
self.format_strs = format_strs
self.prevlogger = None
def __enter__(self):
self.prevlogger = Logger.CURRENT
configure(dir=self.dir, format_strs=self.format_strs)
def __exit_... |
(DETECTION_URL, methods=['POST'])
def predict():
if (not (request.method == 'POST')):
return
if request.files.get('image'):
image_file = request.files['image']
image_bytes = image_file.read()
img = Image.open(io.BytesIO(image_bytes))
results = model(img, size=640)
... |
class SmithyLexer(RegexLexer):
name = 'Smithy'
url = '
filenames = ['*.smithy']
aliases = ['smithy']
version_added = '2.10'
unquoted = '[A-Za-z0-9_\\.#$-]+'
identifier = '[A-Za-z0-9_\\.#$-]+'
simple_shapes = ('use', 'byte', 'short', 'integer', 'long', 'float', 'document', 'double', 'bigI... |
class PairChallengeCommand(PairCommandBase):
def __init__(self, device_id: str, challenge_type: Union[(int, str)], pairing_token: Union[(int, str)], pin: str, device_type: str) -> None:
super().__init__(device_id, device_type, 'FINISH_PAIR')
self.CHALLENGE_TYPE = int(challenge_type)
self.PAI... |
def get_dataset(config, load_only_val=False, use_gt_inssem=False):
if (config.dataset_class == 'panopli'):
if use_gt_inssem:
(instance_dir, semantics_dir, instance_to_semantic_key) = ('rs_instance', 'rs_semantics', 'rs_instance_to_semantic')
else:
(instance_dir, semantics_dir... |
class MaskShadowGANOptions(BaseOptions):
def __init__(self, training):
BaseOptions.__init__(self)
if training:
self.parser.add_argument('--dirA', type=str, required=True, help='Path to training shadow dataset')
self.parser.add_argument('--dirB', type=str, required=True, help=... |
def test_byhand_awav2vel():
CRVAL3A = (6560 * u.AA).to(u.m).value
CDELT3A = (1.0 * u.AA).to(u.m).value
CUNIT3A = 'm'
CRPIX3A = 1.0
restwl = air_to_vac((6562.81 * u.AA))
RESTWAV = restwl.to(u.m).value
CRVAL3V = (CRVAL3A * u.m).to((u.m / u.s), u.doppler_optical(restwl)).value
CDELT3V = (((... |
def parse_args():
parser = argparse.ArgumentParser(description='Link prediction for knowledge graphs')
parser.add_argument('--lr', type=float, default=0.003, help='learning rate (default: 0.003)')
parser.add_argument('--l2', type=float, default=0.0, help='Weight decay value to use in the optimizer. Default:... |
def test_targetstrategy_steering(tmpdir, multiproc_backend):
ys = YadageSteering.create(dataarg=('local:' + os.path.join(str(tmpdir), 'workdir')), workflow='workflow.yml', toplevel='tests/testspecs/nestedmapreduce', initdata={'input': [1, 2, 3]})
ys.adage_argument(default_trackers=False)
ys.adage_argument(*... |
def newtype_attrs_typed_attrs(draw: DrawFn, defaults=None, kw_only=None):
default = NOTHING
class NewTypeAttrs():
a: int
if ((defaults is True) or ((defaults is None) and draw(booleans()))):
default = NewTypeAttrs(draw(integers()))
NewAttrs = NewType('NewAttrs', NewTypeAttrs)
return ... |
class TestKeywordSelection():
def test_select_simple(self, pytester: Pytester) -> None:
file_test = pytester.makepyfile('\n def test_one():\n assert 0\n class TestClass(object):\n def test_method_one(self):\n assert 42 == 43\n ')
... |
def split_complex(comp_num_str):
split_indices = [m.start() for m in re.finditer('[+-]?(\\d+[/.])?\\d+', comp_num_str)]
if (len(split_indices) != 2):
raise Exception(("Somthing must be wrong with the regex, can't seem to handle this complex number : %s" % comp_num_str))
return (comp_num_str[split_in... |
class TestSPoint(unittest.TestCase):
def test_latitude_validity(self):
lon = 0
lat = np.pi
with pytest.raises(ValueError):
SPoint(lon, lat)
lon = 0
lat = np.inf
with pytest.raises(ValueError):
SPoint(lon, lat)
def test_longitude_validity(se... |
class TPlaylistPlugins(TestCase):
class MockBrowser(Browser):
def __init__(self):
super().__init__()
self.activated = False
def activate(self):
self.activated = True
def get_toplevel(self):
return self
def is_toplevel(self):
... |
def test_mouseInteraction():
pg.setConfigOption('mouseRateLimit', (- 1))
plt = pg.PlotWidget()
plt.show()
plt.scene().minDragTime = 0
vline = plt.addLine(x=0, movable=True)
hline = plt.addLine(y=0, movable=True)
hline2 = plt.addLine(y=(- 1), movable=False)
plt.setXRange((- 10), 10)
p... |
def test_relevant_connections():
cm = connectivity.relevant_connections(2, (0, 1), (1,))
answer = np.array([[0, 1], [0, 1]])
assert np.array_equal(cm, answer)
cm = connectivity.relevant_connections(3, (0, 1), (0, 2))
answer = np.array([[1, 0, 1], [1, 0, 1], [0, 0, 0]])
assert np.array_equal(cm, ... |
class Grammar():
def __init__(self, rules):
self.rules = frozenset(rules)
def __eq__(self, other):
return (self.rules == other.rules)
def __str__(self):
return (('\n' + '\n'.join(sorted((repr(x) for x in self.rules)))) + '\n')
def __repr__(self):
return str(self) |
def BuildObservations(Trajectory, MaxOrder):
VPrint('building observations')
LoopCounter = 0
for record in Trajectory:
LoopCounter += 1
if ((LoopCounter % 1000) == 0):
VPrint(LoopCounter)
trajectory = record[1]
for order in range(2, (MaxOrder + 2)):
Su... |
def graphite_electrolyte_exchange_current_density_Ramadass2004(c_e, c_s_surf, c_s_max, T):
m_ref = (4.854 * (10 ** (- 6)))
E_r = 37480
arrhenius = np.exp(((E_r / pybamm.constants.R) * ((1 / 298.15) - (1 / T))))
return ((((m_ref * arrhenius) * (c_e ** 0.5)) * (c_s_surf ** 0.5)) * ((c_s_max - c_s_surf) **... |
class PerDollar(EquityCommissionModel):
def __init__(self, cost=DEFAULT_PER_DOLLAR_COST):
self.cost_per_dollar = float(cost)
def __repr__(self):
return '{class_name}(cost_per_dollar={cost})'.format(class_name=self.__class__.__name__, cost=self.cost_per_dollar)
def calculate(self, order, tran... |
def patch_cfg_for_new_paths(nested_dict, patch):
if (patch is None):
print('Nothing to patch')
return nested_dict
if (not isinstance(nested_dict, (dict, DictConfig))):
return nested_dict
for (key, value) in nested_dict.items():
if isinstance(value, (dict, DictConfig)):
... |
def rebuild_col_unit_col(valid_col_units, col_unit, kmap):
if (col_unit is None):
return col_unit
(agg_id, col_id, distinct) = col_unit
if ((col_id in kmap) and (col_id in valid_col_units)):
col_id = kmap[col_id]
if DISABLE_DISTINCT:
distinct = None
return (agg_id, col_id, di... |
def process_remaining_strings(remaining_strings: Union[(str, List[str])]):
def parse_string(s: str):
s = s.strip().replace('--', '')
if (' ' in s):
(k, v) = s.split(' ')
elif ('=' in s):
(k, v) = s.split('=')
else:
(k, v) = (s, 'True')
retu... |
class NonSynthTextColumn(WideTextColumn):
can_edit = True
def __row_edited(self, render, path, new: str, model: Gtk.TreeModel) -> None:
print_d(f'Trying to edit {self.header_name} to {new!r}')
model[path][0][self.header_name] = new
model.path_changed(path)
def __init__(self, model, t... |
def returndatacopy(computation: BaseComputation) -> None:
(mem_start_position, returndata_start_position, size) = computation.stack_pop_ints(3)
if ((returndata_start_position + size) > len(computation.return_data)):
raise OutOfBoundsRead(f'Return data length is not sufficient to satisfy request. Asked ... |
def has_no_keywords(example):
keywords = ['def ', 'class ', 'for ', 'while ']
lines = example['content'].splitlines()
for line in lines:
for keyword in keywords:
if (keyword in line.lower()):
return {'has_no_keywords': False}
return {'has_no_keywords': True} |
def test_update_page_error_section(db):
page = Page.objects.first()
section = page.sections.first()
section.locked = True
section.save()
instance = QuestionSet.objects.exclude(pages=page).first()
with pytest.raises(ValidationError):
QuestionSetLockedValidator(instance)({'pages': [page], ... |
('/v1/superusers/users/<username>/sendrecovery')
_only
_if(features.SUPER_USERS)
_if(features.MAILING)
class SuperUserSendRecoveryEmail(ApiResource):
_fresh_login
_not_prod
('sendInstallUserRecoveryEmail')
_scope(scopes.SUPERUSER)
def post(self, username):
if (app.config['AUTHENTICATION_TYPE... |
def test_mypy_config_file(testdir, xdist_args):
testdir.makepyfile('\n def pyfunc(x):\n return x * 2\n ')
result = testdir.runpytest_subprocess('--mypy', *xdist_args)
mypy_file_checks = 1
mypy_status_check = 1
mypy_checks = (mypy_file_checks + mypy_status_check)
... |
def configure_shot(net, logger, args):
logger.debug('---- Configuring SHOT ----')
if (args.arch == 'tanet'):
classifier = net.module.new_fc
ext = net
ext.module.new_fc = nn.Identity()
for (k, v) in classifier.named_parameters():
v.requires_grad = False
else:
... |
def read_cameras_text(path):
cameras = {}
with open(path, 'r') as fid:
while True:
line = fid.readline()
if (not line):
break
line = line.strip()
if ((len(line) > 0) and (line[0] != '#')):
elems = line.split()
... |
def get_omitted_any(disallow_any: bool, fail: MsgCallback, note: MsgCallback, orig_type: Type, options: Options, fullname: (str | None)=None, unexpanded_type: (Type | None)=None) -> AnyType:
if disallow_any:
nongen_builtins = get_nongen_builtins(options.python_version)
if (fullname in nongen_builtin... |
def _get_beat_token(beat, strength, i_beat, n_beat):
l = [([0] * N_DIMENSION)]
l[0][DIMENSION['beat']] = preset_event2word['beat'][('Beat_%d' % beat)]
l[0][DIMENSION['strength']] = strength
l[0][DIMENSION['i_beat']] = i_beat
l[0][DIMENSION['n_beat']] = n_beat
l[0][DIMENSION['p_beat']] = (round((... |
class GridAlgorithmicEnv(AlgorithmicEnv):
MOVEMENTS = ['left', 'right', 'up', 'down']
READ_HEAD_START = (0, 0)
def __init__(self, rows, *args, **kwargs):
self.rows = rows
AlgorithmicEnv.__init__(self, *args, **kwargs)
def _move(self, movement):
named = self.MOVEMENTS[movement]
... |
def get_features_user(mode='train'):
with tf.name_scope('input'):
files = tf.data.Dataset.list_files(user_embedding)
ds = files.apply(tf.contrib.data.parallel_interleave(tf.data.TFRecordDataset, cycle_length=8))
ds = ds.map(_parse_record, num_parallel_calls=8).batch(100000).prefetch(1)
... |
def test_deprecated_alias(recwarn_always):
assert (old_hotness() == 'new hotness')
got = recwarn_always.pop(TrioAsyncioDeprecationWarning)
assert ('test_deprecate.old_hotness is deprecated' in got.message.args[0])
assert ('1.23' in got.message.args[0])
assert ('test_deprecate.new_hotness instead' in... |
class get_loss(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
if ('seg_labelweights' in config['dataset_params']):
seg_num_per_class = config['dataset_params']['seg_labelweights']
seg_labelweights = (seg_num_per_class / np.sum(seg_num_... |
def get_ipc_path(pipe=None):
ipc = 'discord-ipc-'
if pipe:
ipc = f'{ipc}{pipe}'
if (sys.platform in ('linux', 'darwin')):
tempdir = (os.environ.get('XDG_RUNTIME_DIR') or tempfile.gettempdir())
paths = ['.', 'snap.discord', 'app/com.discordapp.Discord', 'app/com.discordapp.DiscordCana... |
class Effect6144(BaseEffect):
type = 'overheat'
def handler(fit, module, context, projectionRange, **kwargs):
for tgtAttr in ('aoeCloudSizeBonus', 'explosionDelayBonus', 'missileVelocityBonus', 'maxVelocityModifier', 'aoeVelocityBonus'):
module.boostItemAttr(tgtAttr, module.getModifiedItemAt... |
class Segmentation2Face(object):
def __init__(self, base_dir='./', in_size=1024, out_size=None, model=None, channel_multiplier=2, narrow=1, key=None, is_norm=True, device='cuda'):
self.facegan = FaceGAN(base_dir, in_size, out_size, model, channel_multiplier, narrow, key, is_norm, device=device)
def proc... |
class InternationalEquityTestCase(WithInternationalPricingPipelineEngine, zf.ZiplineTestCase):
START_DATE = T('2014-01-02')
END_DATE = T('2014-02-06')
EXCHANGE_INFO = pd.DataFrame.from_records([{'exchange': 'XNYS', 'country_code': 'US'}, {'exchange': 'XTSE', 'country_code': 'CA'}, {'exchange': 'XLON', 'coun... |
def run_in_process_group(filename: str, calls: List[Dict[(str, Any)]]):
if torch.distributed.is_initialized():
torch.distributed.destroy_process_group()
processes = []
q = Queue()
wait_event = Event()
for (rank, call) in enumerate(calls):
p = Process(target=init_and_run_process, args... |
class Tishidden(TestCase):
(is_win, 'unix-like hidden')
def test_leading_dot(self):
assert is_hidden(fsnative('.'))
assert is_hidden(fsnative('foo/.bar'))
def test_normal_names_not_hidden(self):
assert (not is_hidden(fsnative('foo')))
assert (not is_hidden(fsnative('.foo/bar'... |
def upgrade(op, tables, tester):
op.add_column('user', sa.Column('company', UTF8CharField(length=255), nullable=True))
op.add_column('user', sa.Column('family_name', UTF8CharField(length=255), nullable=True))
op.add_column('user', sa.Column('given_name', UTF8CharField(length=255), nullable=True))
op.bul... |
def check_client_headers(expected_headers: dict[(str, str)], environ: dict[(str, str)]):
wrong_headers = {}
for (name, expected) in expected_headers.items():
value = environ.get('HTTP_{}'.format(name.upper().replace('-', '_')))
if (value != expected):
wrong_headers[name] = value
... |
.parametrize(('variable', 'quote', 'prefix'), DEFAULT_PATTERN_PRODUCTS)
def test_set_default_pattern(temp_dir, helpers, variable, quote, prefix):
source = RegexSource(str(temp_dir), {'path': 'a/b'})
file_path = ((temp_dir / 'a') / 'b')
file_path.ensure_parent_dir_exists()
file_path.write_text(helpers.de... |
class All2AllVInfo(object):
dims_sum_per_rank: List[int]
B_global: int
B_local: int
B_local_list: List[int]
D_local_list: List[int]
input_split_sizes: List[int] = field(default_factory=list)
output_split_sizes: List[int] = field(default_factory=list)
codecs: Optional[QuantizedCommCodecs]... |
class SawyerPlateSlideEnv(SawyerXYZEnv):
def __init__(self):
goal_low = ((- 0.1), 0.85, 0.02)
goal_high = (0.1, 0.9, 0.02)
hand_low = ((- 0.5), 0.4, 0.05)
hand_high = (0.5, 1, 0.5)
obj_low = (0.0, 0.6, 0.015)
obj_high = (0.0, 0.6, 0.015)
super().__init__(self.... |
class GaPrinter(StrPrinter):
_default_settings = ChainMap({'dict_mode': False, 'derivative_color': None, 'function_color': None, 'basis_vector_color': None}, StrPrinter._default_settings)
function_names = ('acos', 'acosh', 'acot', 'acoth', 'arg', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceiling', 'conjugate'... |
_canonicalize
_specialize
_rewriter([Subtensor])
def local_useless_subtensor(fgraph, node):
if (not node.op.idx_list):
return [node.inputs[0]]
if (not hasattr(fgraph, 'shape_feature')):
return
shape_of = fgraph.shape_feature.shape_of
cdata = get_constant_idx(node.op.idx_list, node.inputs... |
class _SwapNetworkToZZSWAP(cirq.PointOptimizer):
def optimization_at(self, circuit: 'cirq.Circuit', index: int, op: 'cirq.Operation') -> Optional[cirq.PointOptimizationSummary]:
if isinstance(op.gate, SwapNetworkProblemUnitary):
gate = op.gate
return cirq.PointOptimizationSummary(cle... |
def test_parameterassignment():
parass = OSC.ParameterAssignment('param1', 1)
prettyprint(parass.get_element())
parass2 = OSC.ParameterAssignment('param1', 1)
parass3 = OSC.ParameterAssignment('param1', 2)
assert (parass == parass2)
assert (parass != parass3)
parass4 = OSC.ParameterAssignmen... |
.functions
.parametrize('df, column_name, dtype, ignore_exception, expected', [(pd.DataFrame({'a': [1, 2], 'b': [3, 4]}), ['a', 'b'], str, False, pd.DataFrame({'a': ['1', '2'], 'b': ['3', '4']})), (pd.DataFrame({'a': [1, 2], 'b': [3, 4]}), ['b', 'a'], str, False, pd.DataFrame({'a': ['1', '2'], 'b': ['3', '4']})), (pd.D... |
class FakeOsModuleLowLevelFileOpTest(FakeOsModuleTestBase):
def setUp(self):
os.umask(18)
super(FakeOsModuleLowLevelFileOpTest, self).setUp()
def test_open_read_only(self):
file_path = self.make_path('file1')
self.create_file(file_path, contents=b'contents')
file_des = se... |
class BaseCorrMM(OpenMPOp, _NoPythonOp):
check_broadcast = False
__props__ = ('border_mode', 'subsample', 'filter_dilation', 'num_groups', 'unshared')
_direction: Optional[str] = None
params_type = ParamsType(direction=EnumList(('DIRECTION_FORWARD', 'forward'), ('DIRECTION_BACKPROP_WEIGHTS', 'backprop w... |
def main():
vocab = load_vocabulary()
model = build_model(len(vocab.word2index), load_checkpoint=True, checkpoint_epoch=checkpoint_epoch)
bot = BotAgent(model, vocab)
while True:
user_input = input('me: ')
if (user_input.strip() == ''):
continue
response = bot.respons... |
def predict_entry_point():
import argparse
parser = argparse.ArgumentParser(description='Use this to run inference with nnU-Net. This function is used when you want to manually specify a folder containing a trained nnU-Net my_models. This is useful when the nnunet environment variables (nnUNet_results) are not ... |
class MatchesException(object):
expected = attr.ib()
def match(self, other):
expected_type = type(self.expected)
if (type(other) is not expected_type):
return Mismatch('{} is not a {}'.format(other, expected_type))
if (other.args != self.expected.args):
return Mis... |
def test_fully_covered_nrel():
dt = pd.date_range(start='2019-1-1 12:00:00', end='2019-1-1 18:00:00', freq='1h')
snowfall_data = pd.Series([1, 5, 0.6, 4, 0.23, (- 5), 19], index=dt)
expected = pd.Series([False, True, False, True, False, False, True], index=dt)
fully_covered = snow.fully_covered_nrel(sno... |
class GridInfo():
def __init__(self, ratio, num_windows, width, height):
self.ratio = ratio
self.num_windows = num_windows
self.width = width
self.height = height
self.num_rows = 0
self.num_cols = 0
def calc(self, num_windows, width, height):
best_ratio = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.