code stringlengths 281 23.7M |
|---|
class TelegramError(Exception):
__slots__ = ('message',)
def __init__(self, message: str):
super().__init__()
msg = _lstrip_str(message, 'Error: ')
msg = _lstrip_str(msg, '[Error]: ')
msg = _lstrip_str(msg, 'Bad Request: ')
if (msg != message):
msg = msg.capit... |
class PynagError(Exception):
def __init__(self, message, errorcode=None, errorstring=None, *args, **kwargs):
self.errorcode = errorcode
self.message = message
self.errorstring = errorstring
try:
super(PynagError, self).__init__(message, *args, **kwargs)
except Typ... |
def complex_email_validation(test):
if (test.subject != 'email'):
return
message = 'Complex email validation is (intentionally) unsupported.'
return (skip(message=message, description='an invalid domain')(test) or skip(message=message, description='an invalid IPv4-address-literal')(test) or skip(mes... |
_required
_POST
def user_permissions_manage(request, username):
if request.POST.get('user_block'):
return user_block(request, username)
if request.POST.get('user_unblock'):
return user_unblock(request, username)
if request.POST.get('user_trust'):
return user_trust(request, username)
... |
class IBNDenseUnit(nn.Module):
def __init__(self, in_channels, out_channels, dropout_rate, conv1_ibn):
super(IBNDenseUnit, self).__init__()
self.use_dropout = (dropout_rate != 0.0)
bn_size = 4
inc_channels = (out_channels - in_channels)
mid_channels = (inc_channels * bn_size)... |
class EventLoop(asyncio.SelectorEventLoop):
def __init__(self, selector=None):
super(EventLoop, self).__init__(selector)
self.set_exception_handler(EventLoop.handleException)
if (sys.platform != 'win32'):
signals = (signal.SIGTERM, signal.SIGINT)
for s in signals:
... |
class TestDataset(unittest.TestCase):
def setUp(self):
logging.disable(logging.CRITICAL)
def tearDown(self):
logging.disable(logging.NOTSET)
def test_round_robin_zip_datasets(self):
long_dataset = lang_pair_dataset([10, 9, 8, 11])
short_dataset = lang_pair_dataset([11, 9])
... |
def test_do_not_claim_an_almost_expiring_lock_if_a_payment_didnt_occur():
amount = UNIT_TRANSFER_AMOUNT
block_number = BlockNumber(1)
pseudo_random_generator = random.Random()
our_state = factories.NettingChannelEndStateProperties(balance=amount)
partner_state = replace(our_state, address=UNIT_TRANS... |
def test_mel_audio_dataset():
dataset_config = {'metadata_file': 'temp/metadata.txt', 'hop_length': 256, 'batch_mel_length': 64}
dataloader = create_dataloader('AudioMelNoiseDataset', dataset_config=dataset_config, batch_size=4, shuffle=True, num_workers=4, drop_last=False)
for batch in tqdm.tqdm(dataloader... |
def _lw(solver, partInfo, subname, shape, retAll=False):
_ = retAll
if (not solver):
if (utils.isLinearEdge(shape) or utils.isPlanar(shape) or utils.isCylindricalPlane(shape)):
return
return 'a linear edge or edge/face with planar or cylindrical surface'
if utils.isLinearEdge(sha... |
class SSCDataset():
def __init__(self, directory, split='train'):
self.files = {}
self.filenames = []
for ext in SPLIT_FILES[split]:
self.files[EXT_TO_NAME[ext]] = []
for sequence in SPLIT_SEQUENCES[split]:
complete_path = os.path.join(directory, 'sequences', ... |
def test_thread(testdir):
testdir.makepyfile('\n import time\n\n def test_foo():\n time.sleep(2)\n ')
result = testdir.runpytest('--timeout=1', '--timeout-method=thread')
result.stderr.fnmatch_lines(['*++ Timeout ++*', '*~~ Stack of MainThread* ~~*', '*File *, line *, in *', '*++... |
.grid
def test_transformer_group__get_transform_crs():
tg = TransformerGroup('epsg:4258', 'epsg:7415')
if grids_available('nl_nsgi_nlgeo2018.tif', 'nl_nsgi_rdtrans2018.tif', check_all=True):
if PROJ_GTE_91:
assert (len(tg.transformers) == 2)
else:
assert (len(tg.transform... |
class LoginForm(Form):
def __init__(self, view, event_channel_name, account_management_interface):
super().__init__(view, event_channel_name)
self.account_management_interface = account_management_interface
if self.exception:
self.add_child(Alert(view, self.exception.as_user_mess... |
def main():
args = parse_args()
(logger, final_output_dir, tb_log_dir) = create_logger(config, args.cfg, 'validate')
logger.info(pprint.pformat(args))
logger.info(pprint.pformat(config))
gpus = [i for i in range(args.gpus)]
print('=> Using GPUs', gpus)
print('=> Loading data ..')
normali... |
class LastLevelP6P7(nn.Module):
def __init__(self, in_channels, out_channels, in_feature='res5'):
super().__init__()
self.num_levels = 2
self.in_feature = in_feature
self.p6 = nn.Conv2d(in_channels, out_channels, 3, 2, 1)
self.p7 = nn.Conv2d(out_channels, out_channels, 3, 2, ... |
def norm_sensor(name, value):
conversions = {'imu.accel': 1, 'imu.gyro': 0.1, 'servo.current': 1, 'servo.command': 1, 'ap.heading_error': 0.2, 'imu.headingrate_lowpass': 0.1}
c = conversions[name]
def norm_value(value):
return math.tanh((c * value))
if (type(value) == type([])):
return l... |
class IBNbResNet(nn.Module):
def __init__(self, channels, init_block_channels, in_channels=3, in_size=(224, 224), num_classes=1000):
super(IBNbResNet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_modu... |
_model
class pvt_v2_b4(PyramidVisionTransformerImpr):
def __init__(self, **kwargs):
super(pvt_v2_b4, self).__init__(patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-06), depths=[3, 8, 27, 3], sr_ratios=[8, 4... |
def handle_napi_poll(event_info):
(name, context, cpu, time, pid, comm, napi, dev_name, work, budget) = event_info
if (cpu in net_rx_dic.keys()):
event_list = net_rx_dic[cpu]['event_list']
rec_data = {'event_name': 'napi_poll', 'dev': dev_name, 'event_t': time, 'work': work, 'budget': budget}
... |
def assert_rank(tensor, expected_rank, name=None):
if (name is None):
name = tensor.name
expected_rank_dict = {}
if isinstance(expected_rank, six.integer_types):
expected_rank_dict[expected_rank] = True
else:
for x in expected_rank:
expected_rank_dict[x] = True
ac... |
def create_guid(bus: int, vendor: int, product: int, version: int, name: str, signature: int, data: int) -> str:
bus = _swap_le16(bus)
vendor = _swap_le16(vendor)
product = _swap_le16(product)
version = _swap_le16(version)
return f'{bus:04x}0000{vendor:04x}0000{product:04x}0000{version:04x}0000' |
def register_equilibrium_solver(name: str, overwrite: bool=False, reason_to_exclude: Optional[str]=None) -> Callable:
return generic_register(name=name, registrator_name='Equilibrium solver', registry=EQUILIBRIUM_SOLVER_REGISTRY, signature=EQUILIBRIUM_SOLVER_SIGNATURE, overwrite=overwrite, reason_to_exclude=reason_... |
class VoxelBackBone8x(nn.Module):
def __init__(self, model_cfg, input_channels, grid_size, **kwargs):
super().__init__()
self.model_cfg = model_cfg
norm_fn = partial(nn.BatchNorm1d, eps=0.001, momentum=0.01)
self.sparse_shape = (grid_size[::(- 1)] + [1, 0, 0])
self.input_chan... |
def _truncate(basis, contr_scheme, symb, split_name):
contr_b = []
b_index = 0
for (l, n_keep) in enumerate(contr_scheme):
n_saved = 0
if (n_keep > 0):
for segm in basis:
segm_l = segm[0]
if (segm_l == l):
segm_len = len(segm[1]... |
class KiteParamCovariance(KiteParameterGroup):
sigSamplingMethod = QtCore.pyqtSignal(str)
sigSpatialBins = QtCore.pyqtSignal(int)
sigSpatialPairs = QtCore.pyqtSignal(int)
def __init__(self, model, **kwargs):
kwargs['type'] = 'group'
kwargs['name'] = 'Scene.covariance'
self.sp = m... |
class TAudioFormats(TestCase):
def setUp(self):
with temp_filename() as filename:
self.filename = filename
def test_load_non_exist(self):
for t in format_types:
if (not t.is_file):
continue
self.assertRaises(AudioFileError, t, self.filename)
... |
def test_logging_emit_error_supressed(pytester: Pytester) -> None:
pytester.makepyfile("\n import logging\n\n def test_bad_log(monkeypatch):\n monkeypatch.setattr(logging, 'raiseExceptions', False)\n logging.warning('oops', 'first', 2)\n ")
result = pytester.runpytest(... |
class DynamicState(State):
def enter(self, event_data):
logger.debug('%sEntering state %s. Processing callbacks...', event_data.machine.name, self.name)
if hasattr(event_data.model, f'on_enter_{self.name}'):
event_data.machine.callbacks([getattr(event_data.model, f'on_enter_{self.name}')... |
class GatherOpsTest(tf.test.TestCase):
def setUp(self):
boxes = np.array([[3.0, 4.0, 6.0, 8.0], [14.0, 14.0, 15.0, 15.0], [0.0, 0.0, 20.0, 20.0]], dtype=float)
self.boxlist = np_box_list.BoxList(boxes)
self.boxlist.add_field('scores', np.array([0.5, 0.7, 0.9], dtype=float))
self.boxl... |
class PackagesDistributionsPrebuiltTest(fixtures.ZipFixtures, unittest.TestCase):
def test_packages_distributions_example(self):
self._fixture_on_path('example-21.12-py3-none-any.whl')
assert (packages_distributions()['example'] == ['example'])
def test_packages_distributions_example2(self):
... |
class MultiHeadAttention(nn.Module):
def __init__(self, input_dim, embed_dim, num_heads):
super().__init__()
assert ((embed_dim % num_heads) == 0), 'Embedding dimension must be 0 modulo number of heads.'
self.embed_dim = embed_dim
self.num_heads = num_heads
self.head_dim = (e... |
def test_api_error_formatter(testdir, xdist_args):
testdir.makepyfile(bad='\n def pyfunc(x: int) -> str:\n return x * 2\n ')
testdir.makepyfile(conftest="\n def custom_file_error_formatter(item, results, errors):\n return '\\n'.join(\n ... |
class ProgressHooksTestCase(WithSeededRandomPipelineEngine, ZiplineTestCase):
ASSET_FINDER_COUNTRY_CODE = 'US'
START_DATE = pd.Timestamp('2014-01-02', tz='UTC')
END_DATE = pd.Timestamp('2014-01-31', tz='UTC')
PREPOPULATED_TERM_CUTOFF = (END_DATE - pd.Timedelta('2 days'))
def make_seeded_random_popul... |
def plot_entropy(myax, inclass, outclass, label, bins=np.logspace((- 8), 0.5, num=30), show_legend=False, show_xlabel=False, show_ylabel=False):
myax.set_title(str(label), fontsize=12)
myax.set_xscale('log')
myax.hist(inclass, bins=bins, color='red', label='In Class')
myax.hist(outclass, bins=bins, colo... |
def load_model(models_path, model_name, epoch=0):
model_params = load_params(models_path, model_name, epoch)
architecture = ('empty' if ('architecture' not in model_params) else model_params['architecture'])
network_type = model_params['network_type']
if ((architecture == 'sdn') or ('sdn' in model_name)... |
def load_image(file_or_name: str, *, size: Optional[Union[(int, Tuple[(int, int)])]], device: torch.device) -> torch.Tensor:
file = os.path.abspath(os.path.expanduser(file_or_name))
name = file_or_name
images = demo.images()
image: _Image
if os.path.exists(file):
image = LocalImage(file)
... |
def parse_args(script):
parser = argparse.ArgumentParser(description=('few-shot script %s' % script))
parser.add_argument('--dataset', default='CUB', help='CUB/miniImagenet/cross/omniglot/cross_char')
parser.add_argument('--model', default='Conv4', help='model: Conv{4|6} / ResNet{10|18|34|50|101}')
pars... |
def make_zipfile(output_filename, source_dir):
relroot = os.path.abspath(os.path.join(source_dir, os.pardir))
with zipfile.ZipFile(output_filename, 'w', zipfile.ZIP_DEFLATED) as zip:
for (root, dirs, files) in os.walk(source_dir):
zip.write(root, os.path.relpath(root, relroot))
f... |
class TestEuropeanCallOption(QiskitFinanceTestCase):
def setUp(self):
super().setUp()
num_uncertainty_qubits = 3
s_p = 2.0
vol = 0.4
r = 0.05
t_m = (40 / 365)
m_u = (((r - (0.5 * (vol ** 2))) * t_m) + np.log(s_p))
sigma = (vol * np.sqrt(t_m))
m... |
def test_sqliteio_write_updates_progress(tmpfile, view):
worker = MagicMock(canceled=False)
io = SQLiteIO(tmpfile, view.scene, create_new=True, worker=worker)
item = BeePixmapItem(QtGui.QImage())
view.scene.addItem(item)
io.write()
worker.begin_processing.emit.assert_called_once_with(1)
work... |
class Track():
def __init__(self):
self.log_point = time.time()
self.enable_track = False
def track(self, mark):
if (not self.enable_track):
return
if torch.cuda.is_available():
torch.cuda.synchronize()
print('{} memory:'.format(mark), ((torch.... |
def loads(s: str, *, parse_float: ParseFloat=float) -> Dict[(str, Any)]:
src = s.replace('\r\n', '\n')
pos = 0
out = Output(NestedDict(), Flags())
header: Key = ()
while True:
pos = skip_chars(src, pos, TOML_WS)
try:
char = src[pos]
except IndexError:
... |
def check_corr(result: float, correct_solution: float, tol: float=0.001):
if (result.strip() == correct_solution.strip()):
return 1
try:
result = float(result.strip())
correct_solution = float(correct_solution.strip())
return (abs((result - correct_solution)) < tol)
except:
... |
class TCoverManagerBuiltin(TestCase):
def setUp(self):
config.init()
self.main = mkdtemp()
self.dir1 = mkdtemp(dir=self.main)
self.dir2 = mkdtemp(dir=self.main)
(h, self.cover1) = mkstemp('.png', dir=self.main)
os.close(h)
pb = GdkPixbuf.Pixbuf.new(GdkPixbuf.C... |
def qufpn_config(min_level, max_level, weight_method=None):
p = OmegaConf.create()
weight_method = (weight_method or 'fastattn')
quad_method = 'fastattn'
num_levels = ((max_level - min_level) + 1)
node_ids = {(min_level + i): [i] for i in range(num_levels)}
level_last_id = (lambda level: node_id... |
def pitch_each_chunk_with_crepe(directory: str) -> list[str]:
print(f"{ULTRASINGER_HEAD} Pitching each chunk with {blue_highlighted('crepe')}")
midi_notes = []
for filename in sorted([f for f in os.listdir(directory) if f.endswith('.wav')], key=(lambda x: int(x.split('_')[1]))):
filepath = os.path.j... |
class Glm(LossMixin, BaseGlm):
def _is_tuner(self):
return False
def fit(self, X, y, sample_weight=None, offsets=None):
(pro_data, raw_data, pre_pro_out, configs, solver, init_data, inferencer) = self.setup_and_prefit(X=X, y=y, sample_weight=sample_weight, offsets=offsets)
if (get_flavor... |
class Scenario(VersionBase):
_XMLNS = XMLNS
_XSI = XSI
def __init__(self, name, author, parameters, entities, storyboard, roadnetwork, catalog, osc_minor_version=_MINOR_VERSION, license=None, creation_date=None, header_properties=None, variable_declaration=None):
if (not isinstance(entities, Entitie... |
class TestBetaIncGrad():
def test_stan_grad_partial(self):
(a, b, z) = pt.scalars('a', 'b', 'z')
betainc_out = pt.betainc(a, b, z)
betainc_grad = pt.grad(betainc_out, [a, b, z])
f_grad = function([a, b, z], betainc_grad)
decimal_precision = (7 if (config.floatX == 'float64') ... |
class DcardComment(Base, Timestamp):
__tablename__ = 'dcard_comments'
__table_args__ = (UniqueConstraint('id', 'post_id', name='pair_key'),)
id = sa.Column(sa.String(64), primary_key=True)
post_id = sa.Column(sa.Integer, sa.ForeignKey('dcard_posts.id'), nullable=False)
post = relationship('DcardPost... |
def _do_import_class(name, currmodule=None):
path_stack = list(reversed(name.split('.')))
if (not currmodule):
currmodule = path_stack.pop()
try:
target = astroid.MANAGER.ast_from_module_name(currmodule)
while (target and path_stack):
path_part = path_stack.pop()
... |
class F8_User(FC6_User):
removedKeywords = FC6_User.removedKeywords
removedAttrs = FC6_User.removedAttrs
def _getParser(self):
op = FC6_User._getParser(self)
op.add_argument('--lock', action='store_true', default=False, version=F8, help='\n If this is present, the new ... |
def canonicalize_list(smiles_list: Iterable[str], include_stereocenters=True) -> List[str]:
canonicalized_smiles = [canonicalize(smiles, include_stereocenters) for smiles in smiles_list]
canonicalized_smiles = [s for s in canonicalized_smiles if (s is not None)]
return remove_duplicates(canonicalized_smiles... |
class Menu(QtWidgets.QMenu):
_dummyActionForHiddenEntryInKeyMapDialog = QtWidgets.QAction()
def __init__(self, parent=None, name=None):
QtWidgets.QMenu.__init__(self, parent)
if name:
self.setTitle(name)
else:
raise ValueError
try:
self.setTool... |
def test_ls_non_empty():
name1 = 'test_schema1'
name2 = 'test_schema2'
type1 = StructType(fields=[IntType(bits=16)])
type2 = StructType(fields=[IntType(bits=8)])
response = client.post(f'/registry/{name1}', json=to_dict(type1), headers={'Content-Type': 'application/x-recap+json'})
assert (respon... |
class Window(QWidget):
NumRows = 2
NumColumns = 3
def __init__(self):
super(Window, self).__init__()
self.glWidgets = []
mainLayout = QGridLayout()
for i in range(Window.NumRows):
row = []
for j in range(Window.NumColumns):
clearColor =... |
def calculate(file_list: List[str], gt_file_list: List[str], args: argparse.Namespace, mcd_dict: Dict):
for (i, gen_path) in enumerate(file_list):
corresponding_list = list(filter((lambda gt_path: (_get_basename(gt_path) in gen_path)), gt_file_list))
assert (len(corresponding_list) == 1)
gt_... |
def test_scan_while():
def power_of_2(previous_power, max_value):
return ((previous_power * 2), until(((previous_power * 2) > max_value)))
max_value = pt.scalar()
(values, _) = scan(power_of_2, outputs_info=pt.constant(1.0), non_sequences=max_value, n_steps=1024)
out_fg = FunctionGraph([max_valu... |
class ExportAssetsAsZipTests(TestCase):
def setUp(self):
self.request_factory = RequestFactory()
self.request = self.request_factory.get('/')
self.request.user = baker.make('users.User')
self.sponsorship = baker.make(Sponsorship, sponsor__name='Sponsor Name')
self.ModelAdmin ... |
class RHEL7_LogVolData(F21_LogVolData):
removedKeywords = F21_LogVolData.removedKeywords
removedAttrs = F21_LogVolData.removedAttrs
def __init__(self, *args, **kwargs):
F21_LogVolData.__init__(self, *args, **kwargs)
self.mkfsopts = (kwargs.get('mkfsoptions', '') or kwargs.get('mkfsopts', '')... |
def _reshape_4(arr, dim):
npair = ((dim * (dim + 1)) // 2)
if (len(arr) == ((npair * (npair + 1)) // 2)):
return S8Integrals(np.asarray(arr))
if (len(arr) == (npair ** 2)):
return S4Integrals(np.asarray(arr).reshape(((npair,) * 2)))
if (len(arr) == (dim ** 4)):
return S1Integrals... |
def test_create_email_authorization_for_repo(get_monkeypatch):
mock = Mock()
get_monkeypatch.setattr(model.repository, 'create_email_authorization_for_repo', mock)
pre_oci_model.create_email_authorization_for_repo('namespace_name', 'repository_name', 'email')
mock.assert_called_once_with('namespace_name... |
def getCommandFromKernelInfo(info, port):
info = KernelInfo(info)
exe = (info.exe or 'python')
if exe.startswith('.'):
exe = os.path.abspath(os.path.join(EXE_DIR, exe))
if (exe.count(' ') and (exe[0] != '"')):
exe = '"{}"'.format(exe)
startScript = os.path.join(pyzo.pyzoDir, 'pyzoker... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, gate=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.gate1 = GateLayer(p... |
def create_parser() -> Tuple[(argparse.ArgumentParser, argparse.ArgumentParser, argparse._SubParsersAction)]:
parser = argparse.ArgumentParser(description='Video codec baselines.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.a... |
class CoerceTestCase(unittest.TestCase):
if (sys.version_info[0] <= 2):
import contextlib
def subTest(self, **kwargs):
(yield)
examples = {'0.0.0': ('0', '0.0', '0.0.0', '0.0.0+', '0-'), '0.1.0': ('0.1', '0.1+', '0.1-', '0.1.0', '0.01.0', '000.0001.'), '0.1.0+2': ('0.1.0+2', '0.1.0.2... |
class AsyncSchemaTypeMixin():
async def create_async(self, bind=None, checkfirst=False):
if (bind is None):
bind = _bind_or_error(self)
t = self.dialect_impl(bind.dialect)
if ((t.__class__ is not self.__class__) and isinstance(t, SchemaType)):
(await t.create_async(bi... |
class Item():
__slots__ = ('s', 'rule', 'ptr', 'start', 'is_complete', 'expect', 'previous', 'node', '_hash')
def __init__(self, rule, ptr, start):
self.is_complete = (len(rule.expansion) == ptr)
self.rule = rule
self.ptr = ptr
self.start = start
self.node = None
... |
def generate_prompt(data_point):
if data_point['input']:
return f'''Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{data_point['instruction']}
### Input:
{data_point['input']}
### ... |
class Decimation(Object):
input_sample_rate = Frequency.T(xmltagname='InputSampleRate')
factor = Int.T(xmltagname='Factor')
offset = Int.T(xmltagname='Offset')
delay = FloatWithUnit.T(xmltagname='Delay')
correction = FloatWithUnit.T(xmltagname='Correction')
def summary(self):
return ('de... |
class Factory(BaseFactory):
def create_poetry(self, cwd: (Path | None)=None, with_groups: bool=True, io: (IO | None)=None, disable_plugins: bool=False, disable_cache: bool=False) -> Poetry:
if (io is None):
io = NullIO()
base_poetry = super().create_poetry(cwd=cwd, with_groups=with_group... |
class run_in_temp(object):
def __init__(self, path=None):
self._must_delete = False
self._path = path
def __enter__(self):
if (self._path is None):
from tempfile import mkdtemp
self._path = mkdtemp(prefix='pyrocko-test')
self._must_delete = True
... |
_config
def test_tall_add_clients_after_current(manager):
manager.test_window('one')
manager.test_window('two')
manager.test_window('three')
manager.c.layout.previous()
assert_focused(manager, 'two')
manager.test_window('four')
assert (manager.c.layout.info()['main'] == 'one')
assert (ma... |
class LogoPlacementConfigurationModelTests(TestCase):
def setUp(self):
self.config = baker.make(LogoPlacementConfiguration, publisher=PublisherChoices.FOUNDATION, logo_place=LogoPlacementChoices.FOOTER)
def test_get_benefit_feature_respecting_configuration(self):
benefit_feature = self.config.ge... |
def process_obj(obj_file):
sdfcommand = './preprocess/isosurface/computeDistanceField'
mcube_cmd = 'preprocess/isosurface/computeMarchingCubes'
lib_cmd = 'preprocess/isosurface/LIB_PATH'
h5_file = obj_file.replace('.obj', '_sdf.h5')
num_sample = (65 ** 3)
bandwidth = 0.1
sdf_res = 256
ex... |
def train_loop(dataloader, model, optimizer):
for (batch, (feat, ret)) in enumerate(train_dl):
loss = model.run_model(feat, ret)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if ((batch % 10) == 0):
print(f'batch: {batch}, loss: {loss.item()}') |
class TestOtherCertificate():
def test_unsupported_subject_public_key_info(self, backend):
cert = _load_cert(os.path.join('x509', 'custom', 'unsupported_subject_public_key_info.pem'), x509.load_pem_x509_certificate)
with pytest.raises(ValueError):
cert.public_key()
def test_bad_time_... |
def load_image_label_from_xml(img_name, voc12_root):
from xml.dom import minidom
elem_list = minidom.parse(os.path.join(voc12_root, ANNOT_FOLDER_NAME, (decode_int_filename(img_name) + '.xml'))).getElementsByTagName('name')
multi_cls_lab = np.zeros(N_CAT, np.float32)
for elem in elem_list:
cat_na... |
class _SocketType(SocketType):
def __init__(self, sock: _stdlib_socket.socket):
if (type(sock) is not _stdlib_socket.socket):
raise TypeError(f"expected object of type 'socket.socket', not '{type(sock).__name__}'")
self._sock = sock
self._sock.setblocking(False)
self._did... |
_register_func(cls=object, pipeable=True, dispatchable=True)
def make_names(names, unique: bool=True) -> Any:
try:
from slugify import slugify
except ImportError as imerr:
raise ValueError('`make_names()` requires `python-slugify` package.\nTry: pip install -U slugify') from imerr
if isinsta... |
class KeyPressTransition(QSignalTransition):
def __init__(self, receiver, key, target=None):
super(KeyPressTransition, self).__init__(receiver.keyPressed)
self.m_key = key
if (target is not None):
self.setTargetState(target)
def eventTest(self, e):
if super(KeyPressTr... |
class CloudzillaTo(BaseAccount):
__name__ = 'CloudzillaTo'
__type__ = 'account'
__version__ = '0.09'
__status__ = 'testing'
__description__ = 'Cloudzilla.to account plugin'
__license__ = 'GPLv3'
__authors__ = [('Walter Purcaro', '')]
PREMIUM_PATTERN = '<h2>account type</h2>\\s*Premium Ac... |
class FakePipeWrapper():
def __init__(self, filesystem: 'FakeFilesystem', fd: int, can_write: bool, mode: str=''):
self._filesystem = filesystem
self.fd = fd
self.can_write = can_write
self.file_object = None
self.filedes: Optional[int] = None
self.real_file = None
... |
class SignalBlocker(_AbstractSignalBlocker):
def __init__(self, timeout=5000, raising=True, check_params_cb=None):
super().__init__(timeout, raising=raising)
self._signals = []
self.args = None
self.all_args = []
self.check_params_callback = check_params_cb
self.signa... |
class NormalizedToImageCoordinatesTest(tf.test.TestCase):
def test_normalized_to_image_coordinates(self):
normalized_boxes = tf.placeholder(tf.float32, shape=(None, 1, 4))
normalized_boxes_np = np.array([[[0.0, 0.0, 1.0, 1.0]], [[0.5, 0.5, 1.0, 1.0]]])
image_shape = tf.convert_to_tensor([1, ... |
class ArgumentParser(cfargparse.ArgumentParser):
def __init__(self, config_file_parser_class=cfargparse.YAMLConfigFileParser, formatter_class=cfargparse.ArgumentDefaultsHelpFormatter, **kwargs):
super(ArgumentParser, self).__init__(config_file_parser_class=config_file_parser_class, formatter_class=formatter... |
def test_blob_mounting_with_empty_layers(manifest_protocol, pusher, puller, images_with_empty_layer, liveserver_session, app_reloader):
pusher.push(liveserver_session, 'devtable', 'simple', 'latest', images_with_empty_layer, credentials=('devtable', 'password'))
options = ProtocolOptions()
options.scopes = ... |
class Highway(Layer):
def __init__(self, init='glorot_uniform', activation=None, weights=None, W_regularizer=None, b_regularizer=None, activity_regularizer=None, W_constraint=None, b_constraint=None, bias=True, input_dim=None, **kwargs):
warnings.warn('The `Highway` layer is deprecated and will be removed a... |
def custom_noise_schedule(timesteps, p):
scale = (1000 / timesteps)
beta_min = (scale * 0.0001)
beta_max = 1
betas = [beta_max]
for i in range(1, timesteps):
beta_i = (((beta_max ** (1 / p)) + ((i / (timesteps - 1)) * ((beta_min ** (1 / p)) - (beta_max ** (1 / p))))) ** p)
betas.appe... |
class Effect6174(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Medium Projectile Turret')), 'maxRange', ship.getModifiedItemAttr('roleBonusCBC'), **kwargs)
fit.modules.filteredItemBoost... |
class ContextMeta(type):
def __new__(cls, name, bases, dct, **kwargs):
def __enter__(self):
self.__class__.context_class.get_contexts().append(self)
self._config_context = None
if hasattr(self, '_pytensor_config'):
self._config_context = pytensor.config.ch... |
def test_inspector_with_nested_exception() -> None:
try:
nested_exception()
except RuntimeError as e:
inspector = Inspector(e)
assert (inspector.exception == e)
assert inspector.has_previous_exception()
assert (inspector.previous_exception is not None)
assert (ins... |
def replace_modules_with_new_variants(manager: BuildManager, graph: dict[(str, State)], old_modules: dict[(str, (MypyFile | None))], new_modules: dict[(str, (MypyFile | None))]) -> None:
for id in new_modules:
preserved_module = old_modules.get(id)
new_module = new_modules[id]
if (preserved_... |
class OnlineProductsDataset(H5PYDataset):
_filename = 'online_products/online_products.hdf5'
def __init__(self, which_sets, **kwargs):
try:
path = '/home/zwz/Desktop/DML/lib/datasets/data/online_products/online_products.hdf5'
except IOError as e:
msg = (str(e) + '.\n ... |
class Issue69_BadV1Year(TestCase):
def test_missing_year(self):
tag = ParseID3v1(b'ABCTAGhello world\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\... |
def _get_stream_params(command: str):
arg_names = ['base', 'audio', 'video']
command_args: Dict = {arg: [] for arg in arg_names}
current_arg = arg_names[0]
for part in shlex.split(command):
arg_name = part[2:]
if (arg_name in arg_names):
current_arg = arg_name
else:
... |
class TFMobileViTASPPPooling(tf.keras.layers.Layer):
def __init__(self, config: MobileViTConfig, out_channels: int, **kwargs) -> None:
super().__init__(**kwargs)
self.global_pool = tf.keras.layers.GlobalAveragePooling2D(keepdims=True, name='global_pool')
self.conv_1x1 = TFMobileViTConvLayer(... |
def load_fips_ecdsa_key_pair_vectors(vector_data):
vectors = []
key_data = None
for line in vector_data:
line = line.strip()
if ((not line) or line.startswith('#')):
continue
if (line[1:(- 1)] in _ECDSA_CURVE_NAMES):
curve_name = _ECDSA_CURVE_NAMES[line[1:(- 1... |
class PutExecutor(ActionExecutor):
def __init__(self, relation: Relation):
self.relation = relation
def execute(self, script: Script, state: EnvironmentState, info: ExecutionInfo, char_index, modify=True, in_place=False):
current_line = script[0]
info.set_current_line(current_line)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.