code stringlengths 281 23.7M |
|---|
def blksize(path):
if (os.name != 'nt'):
size = os.statvfs(path).f_bsize
else:
import ctypes
drive = (os.path.splitdrive(os.path.abspath(path))[0] + '\\')
cluster_sectors = ctypes.c_longlong(0)
sector_size = ctypes.c_longlong(0)
ctypes.windll.kernel32.GetDiskFreeS... |
class TestReporter(Dataset):
def __init__(self, multi_task_instance):
self.test_task = multi_task_instance
self.task_type = multi_task_instance.dataset_type
self.config = registry.get('config')
self.writer = registry.get('writer')
self.report = []
self.timer = Timer()... |
def rewrite_record(bdist_dir: str) -> None:
info_dir = _dist_info_dir(bdist_dir)
record_path = pjoin(info_dir, 'RECORD')
record_relpath = relpath(record_path, bdist_dir)
sig_path = pjoin(info_dir, 'RECORD.jws')
if exists(sig_path):
os.unlink(sig_path)
def walk() -> Generator[(str, None, ... |
class FMaxListener(Listener):
def __init__(self, name, beta=1):
self.beta = beta
self.fname = _timestamped_filename(('%s-Fmax' % name))
smokesignal.on('evaluation_finished', self.on_evaluation_finished)
super().__init__()
def on_evaluation_finished(self, evaluation, dataset, pred... |
(StepsRunner, 'run_step_group')
def test_run_step_groups_sequence(mock_run_step_group):
StepsRunner(get_valid_test_pipeline(), Context()).run_step_groups(groups=['sg3', 'sg1', 'sg2', 'sg4'], success_group='arb success', failure_group='arb fail')
assert (mock_run_step_group.mock_calls == [call('sg3'), call('sg1'... |
class Base(object):
type = None
parent = None
children = ()
was_changed = False
was_checked = False
def __new__(cls, *args, **kwds):
assert (cls is not Base), 'Cannot instantiate Base'
return object.__new__(cls)
def __eq__(self, other):
if (self.__class__ is not other... |
def get_valid_stats(trainer):
stats = OrderedDict()
stats['valid_loss'] = trainer.get_meter('valid_loss').avg
if (trainer.get_meter('valid_nll_loss').count > 0):
nll_loss = trainer.get_meter('valid_nll_loss').avg
stats['valid_nll_loss'] = nll_loss
else:
nll_loss = trainer.get_met... |
def build_optimizer(args, model):
params_with_decay = []
params_without_decay = []
for (name, param) in model.named_parameters():
if (param.requires_grad is False):
continue
if (args.only_prompt_loss and (name.find('clip_model') != (- 1))):
continue
if (args.f... |
class Effect6561(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
lvl = src.level
fit.fighters.filteredItemBoost((lambda mod: mod.item.requiresSkill('Light Fighters')), 'maxVelocity', (src.getModifiedItemAttr('maxVelocityBonus') * lvl), **kwargs) |
def GetLineWidth(line):
if isinstance(line, unicode):
width = 0
for uc in unicodedata.normalize('NFC', line):
if (unicodedata.east_asian_width(uc) in ('W', 'F')):
width += 2
elif (not unicodedata.combining(uc)):
width += 1
return width
... |
class Agilent34410A(Instrument):
voltage_dc = Instrument.measurement('MEAS:VOLT:DC? DEF,DEF', 'DC voltage, in Volts')
voltage_ac = Instrument.measurement('MEAS:VOLT:AC? DEF,DEF', 'AC voltage, in Volts')
current_dc = Instrument.measurement('MEAS:CURR:DC? DEF,DEF', 'DC current, in Amps')
current_ac = Inst... |
class MouseHandler():
def __init__(self, interface, loglevel):
logger.debug('Initializing %s: (interface: %s, loglevel: %s)', self.__class__.__name__, interface, loglevel)
self.interface = interface
self.alignments = interface.alignments
self.frames = interface.frames
self.ex... |
_on_failure
.parametrize('number_of_nodes', [2])
def test_settle_is_automatically_called(raiden_network: List[RaidenService], token_addresses: List[TokenAddress]) -> None:
(app0, app1) = raiden_network
registry_address = app0.default_registry.address
token_address = token_addresses[0]
token_network_addr... |
.parametrize('delayed', [True, False])
def test_zero_timeout(qtbot, timer, delayed, signaller):
with qtbot.waitSignal(signaller.signal, raising=False, timeout=0) as blocker:
if delayed:
timer.single_shot(signaller.signal, 0)
else:
signaller.signal.emit()
assert (blocker.s... |
class GeneralTab(QWidget):
def __init__(self, fileInfo, parent=None):
super(GeneralTab, self).__init__(parent)
fileNameLabel = QLabel('File Name:')
fileNameEdit = QLineEdit(fileInfo.fileName())
pathLabel = QLabel('Path:')
pathValueLabel = QLabel(fileInfo.absoluteFilePath())
... |
def is_no_type_check_decorator(expr: ast3.expr) -> bool:
if isinstance(expr, Name):
return (expr.id == 'no_type_check')
elif isinstance(expr, Attribute):
if isinstance(expr.value, Name):
return ((expr.value.id == 'typing') and (expr.attr == 'no_type_check'))
return False |
def validate(mw_model, model, val_loader):
mw_model.eval()
model.eval()
(scores, gt_scores) = ([], [])
for (num, val_batch) in enumerate(val_loader):
(im_mw, imp_iwt, gt_iwt, im_dmos) = val_batch
print(im_mw.size())
pre_iwt = mw_model(im_mw)
pre_iwt = [LocalNormalization(... |
def rank_vote(key: str, match: typing.Dict[(int, typing.List[typing.List[typing.Dict[(str, str)]]])], scores: typing.List[typing.Dict[(str, float)]]) -> typing.List[typing.List[typing.Dict[(str, str)]]]:
queries_rank = []
for (documents_query, scores_query) in zip(match.values(), scores):
query_rank = [... |
def conv_init(m):
classname = m.__class__.__name__
if (classname.find('Conv') != (- 1)):
init.xavier_uniform(m.weight, gain=math.sqrt(2))
init.constant(m.bias, 0)
elif (classname.find('BatchNorm') != (- 1)):
init.constant(m.weight, 1)
init.constant(m.bias, 0) |
class TestCreateNotify(EndianTest):
def setUp(self):
self.evt_args_0 = {'border_width': 56468, 'height': 7111, 'override': 0, 'parent': , 'sequence_number': 31058, 'type': 151, 'width': 44173, 'window': , 'x': (- 21847), 'y': (- 22248)}
self.evt_bin_0 = b'\x97\x00Ry\xe9\xfc\x8a,\x1f\xc0E4\xa9\xaa\x1... |
def parse_opt():
parser = argparse.ArgumentParser()
parser.add_argument('--data_folder', type=str, help='folder with data files saved by create_input_files.py.', default='')
parser.add_argument('--model_path', type=str, help='path for pretrained ResNet.', default='')
parser.add_argument('--word_map_file... |
class GroupNormalization(Layer):
' Group Normalization\n from: shoanlu GAN:
def __init__(self, axis=(- 1), gamma_init='one', beta_init='zero', gamma_regularizer=None, beta_regularizer=None, epsilon=1e-06, group=32, data_format=None, **kwargs):
self.beta = None
self.gamma = None
s... |
class GeneralPriceProvider(DataProvider):
def __init__(self, bloomberg: BloombergDataProvider=None, quandl: QuandlDataProvider=None, haver: HaverDataProvider=None):
super().__init__()
self._ticker_type_to_data_provider_dict = {}
for provider in [bloomberg, quandl, haver]:
if (pro... |
def _concatkdf_derive(key_material: bytes, length: int, auxfn: typing.Callable[([], hashes.HashContext)], otherinfo: bytes) -> bytes:
utils._check_byteslike('key_material', key_material)
output = [b'']
outlen = 0
counter = 1
while (length > outlen):
h = auxfn()
h.update(_int_to_u32be... |
def info_verbose(log_info, e_epoch=None, path=None):
from scipy.ndimage.filters import gaussian_filter1d
epochs = log_info['epoch']
end_epoch = (epochs[(- 1)] if (not e_epoch) else e_epoch)
(f, (ax1, ax2)) = plt.subplots(2, sharex=True, sharey=False)
trans = 0.3
ax1.plot(epochs[:end_epoch], log_... |
class SpatialGate(nn.Module):
def __init__(self):
super(SpatialGate, self).__init__()
kernel_size = 7
self.compress = ChannelPool()
self.spatial = BasicConv(2, 1, kernel_size, stride=1, padding=((kernel_size - 1) // 2))
def forward(self, x):
x_compress = self.compress(x)
... |
def process_all_speaker_f0(speaker_directory, fs, window, hop, voiced_prob_cutoff=0.2):
all_speakers = sorted(os.listdir(speaker_directory))
all_speaker_f0_info = {}
for speaker_id in all_speakers:
print(f'Processing speaker {speaker_id}...')
speaker_utt_path = os.path.join(speaker_directory... |
class SortDataset(BaseWrapperDataset):
def __init__(self, dataset, sort_order):
super().__init__(dataset)
if (not isinstance(sort_order, (list, tuple))):
sort_order = [sort_order]
self.sort_order = sort_order
assert all(((len(so) == len(dataset)) for so in sort_order))
... |
def try_finally_resolve_control(builder: IRBuilder, cleanup_block: BasicBlock, finally_control: FinallyNonlocalControl, old_exc: Value, ret_reg: ((Register | AssignmentTarget) | None)) -> BasicBlock:
(reraise, rest) = (BasicBlock(), BasicBlock())
builder.add(Branch(old_exc, rest, reraise, Branch.IS_ERROR))
... |
class TestSvdTrainingExtensions(unittest.TestCase):
def test_svd_layer_selection_without_mo(self):
tf.compat.v1.reset_default_graph()
svd = s.Svd(None, None, s.CostMetric.memory)
svd._svd = create_autospec(pymo.Svd, instance=True)
x = tf.compat.v1.placeholder(tf.float32, [None, 784],... |
def test_disk_and_tensorflow_logger():
args_line = FAST_LOCAL_TEST_ARGS
args_line += ' --log disk tensorboard'
result = run_main(args_line, 'results_test_loggers', clean_run=True)
experiment_dir = Path(result[(- 1)])
assert experiment_dir.is_dir()
raw_logs = list(experiment_dir.glob('raw_log-*.t... |
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [migrations.CreateModel(name='Site', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200))]), migrations.CreateModel(name='Post... |
class TestTriangulation():
def setup_method(self):
gdf = gpd.read_file(geodatasets.get_path('geoda liquor_stores')).explode(ignore_index=True)
self.gdf = gdf[(~ gdf.geometry.duplicated())]
self.gdf_str = self.gdf.set_index('placeid')
.parametrize('method', TRIANGULATIONS)
def test_tr... |
.parametrize('valuetrigger', [OSC.ParameterCondition('asdf', 1, OSC.Rule.greaterOrEqual), OSC.VariableCondition('asdf', 1, OSC.Rule.greaterOrEqual), OSC.TimeOfDayCondition(OSC.Rule.greaterOrEqual, 2023, 4, 5, 6, 4, 8), OSC.SimulationTimeCondition(2, OSC.Rule.greaterOrEqual), OSC.StoryboardElementStateCondition(OSC.Stor... |
def train(train_queue, valid_queue, model, architect, criterion, optimizer, lr, epoch, analyzer):
objs = utils.AvgrageMeter()
top1 = utils.AvgrageMeter()
top5 = utils.AvgrageMeter()
for (step, (input, target)) in enumerate(train_queue):
model.train()
n = input.size(0)
input = inp... |
(repr=False, eq=False)
class SignedBlindedBalanceProof():
channel_identifier: ChannelID
token_network_address: TokenNetworkAddress
nonce: Nonce
additional_hash: AdditionalHash
chain_id: ChainID
balance_hash: BalanceHash
signature: Signature
non_closing_signature: Optional[Signature] = fi... |
class traindataset(data.Dataset):
def __init__(self, root, mode, transform=None, num_class=5, multitask=False):
self.root = os.path.expanduser(root)
self.transform = transform
self.mode = mode
self.train_data = []
self.train_label = []
self.test_data = []
self... |
def _quantize(module: nn.Module, inplace: bool, output_type: torch.dtype=torch.float, quant_state_dict_split_scale_bias: bool=False, per_table_weight_dtypes: Optional[Dict[(str, torch.dtype)]]=None) -> nn.Module:
if quant_state_dict_split_scale_bias:
quant_prep_enable_quant_state_dict_split_scale_bias_for_t... |
class ConfigTestCase(unittest.TestCase):
def test_sections(self):
config = Configuration()
self.assertSetEqual(set(config._parser.sections()), {'SERVICE', 'FRONTEND'})
def test_get_option(self):
config = Configuration()
self.assertEqual(config.get_option('SERVICE', 'name'), 'loca... |
.parametrize('creator', sorted((set(PythonInfo.current_system().creators().key_to_class) - {'builtin'})))
.usefixtures('session_app_data')
def test_create_distutils_cfg(creator, tmp_path, monkeypatch):
result = cli_run([str((tmp_path / 'venv')), '--activators', '', '--creator', creator, '--setuptools', 'bundle', '-... |
_test
.skipif((K.backend() != 'tensorflow'), reason='Requires tensorflow backend')
def test_TensorBoard(tmpdir):
np.random.seed(np.random.randint(1, .0))
filepath = str((tmpdir / 'logs'))
((X_train, y_train), (X_test, y_test)) = get_test_data(num_train=train_samples, num_test=test_samples, input_shape=(inpu... |
class menu(page):
def __init__(self, name, items):
super(menu, self).__init__(name)
self.selection = 0
self.items = items
self.prev = False
self.last_selection = (- 1)
self.menu_values = {}
def find_parents(self):
for p in self.items:
p.lcd = s... |
class STM32F1xxAdc(QlPeripheral):
class Type(ctypes.Structure):
_fields_ = [('SR', ctypes.c_uint32), ('CR1', ctypes.c_uint32), ('CR2', ctypes.c_uint32), ('SMPR1', ctypes.c_uint32), ('SMPR2', ctypes.c_uint32), ('JOFR1', ctypes.c_uint32), ('JOFR2', ctypes.c_uint32), ('JOFR3', ctypes.c_uint32), ('JOFR4', ctype... |
class VertexArray():
def __init__(self):
self._context = pyglet.gl.current_context
self._id = GLuint()
glGenVertexArrays(1, self._id)
def id(self):
return self._id.value
def bind(self):
glBindVertexArray(self._id)
def unbind():
glBindVertexArray(0)
def... |
def load_model(config, ckpt, gpu, eval_mode):
if ckpt:
pl_sd = torch.load(ckpt, map_location='cpu')
global_step = pl_sd['global_step']
print(f'loaded model from global step {global_step}.')
else:
pl_sd = {'state_dict': None}
global_step = None
model = load_model_from_... |
def test_context_cosine(local_client, grpc_client):
def f(client: QdrantBase, **kwargs: Dict[(str, Any)]) -> List[models.ScoredPoint]:
return client.discover(collection_name=COLLECTION_NAME, context=[models.ContextExamplePair(positive=10, negative=19)], with_payload=True, limit=1000, using='image')
com... |
.slow
(deadline=None)
(chunk_size=integers(min_value=1, max_value=(2 ** 12)), mode=sampled_from(list(brotlicffi.BrotliEncoderMode)), quality=integers(min_value=0, max_value=11), lgwin=integers(min_value=10, max_value=24), lgblock=one_of(integers(min_value=0, max_value=0), integers(min_value=16, max_value=24)))
def test... |
class Image(collections.namedtuple('Image', image_fields)):
def to_str_row(self):
return ('%d\t%d\t%d\t%s\t%s' % (self.width, self.height, self.file_size, self.type, self.path.replace('\t', '\\t')))
def to_str_row_verbose(self):
return ('%d\t%d\t%d\t%s\t%s\t##%s' % (self.width, self.height, self... |
class ListDatatableDataTest(unittest.TestCase):
def setUpClass(cls):
datatable_data = {'datatable': DatatableDataFactory.build()}
meta = {'meta': DatatableMetaFactory.build()}
datatable_data.update(meta)
re.compile(' body=json.dumps(datatable_data))
re.compile(' body=json.d... |
def make_transform(dataset, transform_fragments, property_info_list, rule_selection_function, substructure_pat=None, min_radius=0, min_pairs=0, min_variable_size=0, min_constant_size=0, max_variable_size=9999, pool=None, cursor=None, explain=None):
if (explain is None):
explain = reporters.no_explain
if... |
class EasyTag(BaseDbModel):
class Meta():
table = 'easytags'
id = fields.BigIntField(pk=True)
guild_id = fields.BigIntField()
channel_id = fields.BigIntField(index=True)
delete_after = fields.BooleanField(default=False)
def _guild(self) -> Optional[discord.Guild]:
return self.bot... |
class TestReadOnly():
def test_write_a_read_only_property(self, request_unmarshaller):
data = json.dumps({'id': 10, 'name': 'Pedro'}).encode()
request = MockRequest(host_url='', method='POST', path='/users', data=data)
result = request_unmarshaller.unmarshal(request)
assert (len(resu... |
class W_ChpContinuationMarkKey(W_InterposeContinuationMarkKey):
import_from_mixin(ChaperoneMixin)
def post_get_cont(self, value, env, cont):
vals = values.Values.make1(value)
return check_chaperone_results(vals, env, imp_cmk_post_get_cont(self.inner, env, cont))
def post_set_cont(self, body,... |
class Dictionary(object):
def __init__(self, pad='<pad>', eos='</s>', unk='<unk>', bos='<s>', extra_special_symbols=None):
(self.unk_word, self.pad_word, self.eos_word) = (unk, pad, eos)
self.symbols = []
self.count = []
self.indices = {}
self.bos_index = self.add_symbol(bos)... |
class KnownValues(unittest.TestCase):
def test_sgx_jk(self):
mol = gto.Mole()
mol.build(verbose=0, atom=[['O', (0.0, 0.0, 0.0)], [1, (0.0, (- 0.757), 0.587)], [1, (0.0, 0.757, 0.587)]], basis='ccpvdz')
nao = mol.nao
mf = scf.UHF(mol)
dm = mf.get_init_guess()
(vjref, v... |
def test_delete_user_policy(initialized_db, app):
policies = model.autoprune.get_namespace_autoprune_policies_by_orgname('devtable')
assert (len(policies) == 1)
policy_uuid = policies[0].uuid
with client_with_identity('devtable', app) as cl:
conduct_api_call(cl, UserAutoPrunePolicy, 'DELETE', {'... |
def _parse_readme(lns):
subres = {}
for ln in [x.strip() for x in lns]:
if (not ln.startswith('*')):
continue
ln = ln[1:].strip()
for k in ['download', 'dataset', 'models', 'model', 'pre-processing']:
if ln.startswith(k):
break
else:
... |
class TestVectorizedSymbolLookup(WithAssetFinder, ZiplineTestCase):
def make_equity_info(cls):
T = partial(pd.Timestamp, tz='UTC')
def asset(sid, symbol, start_date, end_date):
return dict(sid=sid, symbol=symbol, start_date=T(start_date), end_date=T(end_date), exchange='NYSE')
re... |
def nr_e2(eri, mo_coeff, orbs_slice, aosym='s1', mosym='s1', out=None, ao_loc=None):
assert eri.flags.c_contiguous
assert (aosym in ('s4', 's2ij', 's2kl', 's2', 's1'))
assert (mosym in ('s2', 's1'))
mo_coeff = numpy.asfortranarray(mo_coeff)
assert (mo_coeff.dtype == numpy.double)
nao = mo_coeff.... |
def copy_files_from_dict(all_files, target_dir, dest_dir):
for (task_id, files) in all_files.items():
for (file_id, names) in files.items():
to_copy = os.path.join(target_dir, 'GetFiles', names[LOCAL_NAME_KEY])
new_dest_name = os.path.basename(names[REMOTE_NAME_KEY])
ext ... |
class CoreClient(rpc.TCPClient):
def __init__(self, host, open_timeout=5000):
self.packer = Vxi11Packer()
self.unpacker = Vxi11Unpacker('')
super(CoreClient, self).__init__(host, DEVICE_CORE_PROG, DEVICE_CORE_VERS, open_timeout)
def create_link(self, id, lock_device, lock_timeout, name):... |
def to_tensor(data):
if isinstance(data, torch.Tensor):
return data
elif isinstance(data, np.ndarray):
return torch.from_numpy(data)
elif (isinstance(data, Sequence) and (not mmcv.is_str(data))):
return torch.tensor(data)
elif isinstance(data, int):
return torch.LongTenso... |
class Speech2Text2Processor(ProcessorMixin):
feature_extractor_class = 'AutoFeatureExtractor'
tokenizer_class = 'Speech2Text2Tokenizer'
def __init__(self, feature_extractor, tokenizer):
super().__init__(feature_extractor, tokenizer)
self.current_processor = self.feature_extractor
def __c... |
class Gate():
def __init__(self, gate_type, targets, args, boxes, options={}, comments=None):
global orientation
self.type = gate_type
self.position_list = []
self.comments = comments
self.wire_color_changes = {}
self.wire_style_changes = {}
self.wire_type_cha... |
class Migration(migrations.Migration):
dependencies = [('successstories', '0010_story_submitted_by')]
operations = [migrations.AlterField(model_name='story', name='submitted_by', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL))] |
def get_all_QAs(qtotal=100):
page = 1
next = ('/api/v0/qa/all?page=' + str(page))
qas = []
image_map = {}
while True:
data = utils.retrieve_data(next)
for d in data['results']:
if (d['image'] not in image_map):
image_map[d['image']] = get_image_data(id=d['... |
def channel_open(open_queue: List[ChannelNew]) -> None:
for channel_open in open_queue:
channel = channel_details(channel_open.endpoint, channel_open.token_address, channel_open.partner)
assert (channel is None), 'Channel already exists, the operation should not have been scheduled.'
channel... |
def test_struct_with_struct_type():
mock_client = MagicMock(spec=HMS)
class MockTable():
name = 'dummy_table'
columns = [HColumn('col1', HStructType(names=['sub_col1', 'sub_col2'], types=[HPrimitiveType(PrimitiveCategory.BOOLEAN), HPrimitiveType(PrimitiveCategory.INT)]))]
mock_client.get_tab... |
.parametrize('Type', [Bits16, Bits32])
def test_adder(do_test, Type):
def tv_in(model, tv):
model.in_1 = tv[0]
model.in_2 = tv[1]
class A(Component):
def construct(s, Type):
s.in_1 = InPort(Type)
s.in_2 = InPort(Type)
s.out = OutPort(Type)
... |
class BlockListRelease(FilterReleasePlugin):
name = 'blocklist_release'
blocklist_package_names: list[Requirement] = []
def initialize_plugin(self) -> None:
if (not self.blocklist_package_names):
self.blocklist_release_requirements = self._determine_filtered_package_requirements()
... |
class ManagedDockWindow(ManagedWindowBase):
def __init__(self, procedure_class, x_axis=None, y_axis=None, linewidth=1, log_fmt=None, log_datefmt=None, **kwargs):
self.x_axis = x_axis
self.y_axis = y_axis
measure_quantities = []
if isinstance(self.x_axis, list):
measure_qu... |
class PlayAdvancementTab(Packet):
id = 34
to = 0
def __init__(self, action: int, tab_id: int) -> None:
super().__init__()
self.action = action
self.tab_id = tab_id
def decode(cls, buf: Buffer) -> PlayAdvancementTab:
return cls(buf.unpack_varint(), buf.unpack_optional(buf.... |
class unit_gtcn_5(nn.Module):
def __init__(self, in_channels, out_channels, A, coff_embedding=4, num_subset=3):
super(unit_gtcn_5, self).__init__()
inter_channels = (out_channels // coff_embedding)
self.inter_c = inter_channels
self.PA = nn.Parameter(torch.from_numpy(A.astype(np.floa... |
.fast
def test_noplot_different_quantities(*args, **kwargs):
import matplotlib.pyplot as plt
plt.ion()
from radis import load_spec
from radis.test.utils import getTestFile
s = load_spec(getTestFile('CO_Tgas1500K_mole_fraction0.01.spec'), binary=True)
s.update()
s.plot('abscoeff', nfig='test_... |
def testCheckMethodCalls(SAMPLE_PATH_14d9f) -> None:
targetMethod = ['Lcom/google/progress/WifiCheckTask;', 'checkWifiCanOrNotConnectServer', '([Ljava/lang/String;)Z']
checkMethods = []
checkMethods.append(tuple(['Landroid/util/Log;', 'e', '(Ljava/lang/String; Ljava/lang/String;)I']))
assert (checkMetho... |
class BASNet(nn.Module):
def __init__(self, n_channels, n_classes):
super(BASNet, self).__init__()
resnet = models.resnet34(pretrained=True)
self.inconv = nn.Conv2d(n_channels, 64, 3, padding=1)
self.inbn = nn.BatchNorm2d(64)
self.inrelu = nn.ReLU(inplace=True)
self.e... |
class GetDialogs():
async def get_dialogs(self: 'pyrogram.Client', limit: int=0) -> Optional[AsyncGenerator[('types.Dialog', None)]]:
current = 0
total = (limit or ((1 << 31) - 1))
limit = min(100, total)
offset_date = 0
offset_id = 0
offset_peer = raw.types.InputPeer... |
def group_hash_bucket_indices(hash_bucket_object_groups: np.ndarray, num_buckets: int, num_groups: int, object_store: Optional[IObjectStore]=None) -> Tuple[(np.ndarray, List[ObjectRef])]:
object_refs = []
hash_bucket_group_to_obj_id = np.empty([num_groups], dtype='object')
if (hash_bucket_object_groups is N... |
def test_from_dict_interval_logical_type():
logical_type_dict = {'type': 'bytes', 'logical': 'build.recap.Interval', 'bytes': 12, 'variable': False}
recap_type = from_dict(logical_type_dict)
assert isinstance(recap_type, BytesType)
assert (recap_type.logical == logical_type_dict['logical'])
assert (... |
class RHEL7_LogVol(F21_LogVol):
removedKeywords = F21_LogVol.removedKeywords
removedAttrs = F21_LogVol.removedAttrs
def _getParser(self):
op = F21_LogVol._getParser(self)
op.add_argument('--mkfsoptions', dest='mkfsopts', version=RHEL7, help='\n Specifies additional par... |
class Renderer(object):
def render(self, ast):
walker = ast.walker()
self.buf = ''
self.last_out = '\n'
event = walker.nxt()
while (event is not None):
type_ = event['node'].t
if hasattr(self, type_):
getattr(self, type_)(event['node'],... |
class CmdLineHandler(HardwareHandlerBase):
def get_passphrase(self, msg, confirm):
import getpass
print_stderr(msg)
return getpass.getpass('')
def get_pin(self, msg, *, show_strength=True):
t = {'a': '7', 'b': '8', 'c': '9', 'd': '4', 'e': '5', 'f': '6', 'g': '1', 'h': '2', 'i': ... |
class TestDOTAFCOS(TestDOTA):
def eval(self):
txt_name = '{}.txt'.format(self.cfgs.VERSION)
real_test_img_list = self.get_test_image()
fcos = build_whole_network_batch_quad.DetectionNetworkFCOS(cfgs=self.cfgs, is_training=False)
self.test_dota(det_net=fcos, real_test_img_list=real_te... |
def main():
checkpoint_folder = str(os.path.join(args.save_dir, args.exp_name))
if (not os.path.exists(checkpoint_folder)):
os.makedirs(checkpoint_folder)
model = TSCAN()
if (args.pre_trained == 1):
print('Using pre-trained on all ALL AFRL!')
model.load_state_dict(torch.load('./c... |
class BERT2VQ(nn.Module):
def __init__(self, opt) -> None:
super().__init__()
self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
self.bertmodel = BertModel.from_pretrained('bert-base-uncased')
if (opt.gpu_ids[0] != (- 1)):
self.device = f'cuda:{opt.gpu_id... |
class ContentManageableAdminTests(unittest.TestCase):
def make_admin(self, **kwargs):
cls = type('TestAdmin', (ContentManageableModelAdmin,), kwargs)
return cls(mock.Mock(), mock.Mock())
def test_readonly_fields(self):
admin = self.make_admin(readonly_fields=['f1'])
self.assertEq... |
def load_model_ensemble_and_task(filenames, arg_overrides=None, task=None):
from fairseq import tasks
ensemble = []
for filename in filenames:
if (not os.path.exists(filename)):
raise IOError('Model file not found: {}'.format(filename))
state = load_checkpoint_to_cpu(filename, ar... |
def aggregate_wbg(prob, keep_bg=False):
k = prob.shape
new_prob = torch.cat([torch.prod((1 - prob), dim=0, keepdim=True), prob], 0).clamp(1e-07, (1 - 1e-07))
logits = torch.log((new_prob / (1 - new_prob)))
if keep_bg:
return F.softmax(logits, dim=0)
else:
return F.softmax(logits, dim... |
def test_segmented_only_catches_404(cipher_signature):
stream = cipher_signature.streams.filter(adaptive=True)[0]
with mock.patch('pytube.request.stream') as mock_stream:
mock_stream.side_effect = HTTPError('', 403, 'Forbidden', '', '')
with mock.patch('pytube.streams.open', mock.mock_open(), cr... |
def run_experiment(variant):
env_params = variant['env_params']
policy_params = variant['policy_params']
value_fn_params = variant['value_fn_params']
algorithm_params = variant['algorithm_params']
replay_buffer_params = variant['replay_buffer_params']
sampler_params = variant['sampler_params']
... |
def test_phase(opt, net, testloader, log_save_path=None):
with torch.no_grad():
net.eval()
start = time()
avg_frame_rate = 0
mae = 0.0
rmse = 0.0
me = 0.0
for (j, data) in enumerate(testloader):
(inputs, labels) = (data['image'], data['target'])
... |
class SawyerPushWallEnvV2(SawyerXYZEnv):
OBJ_RADIUS = 0.02
def __init__(self):
hand_low = ((- 0.5), 0.4, 0.05)
hand_high = (0.5, 1, 0.5)
obj_low = ((- 0.05), 0.6, 0.015)
obj_high = (0.05, 0.65, 0.015)
goal_low = ((- 0.05), 0.85, 0.01)
goal_high = (0.05, 0.9, 0.02)... |
()
def initialized_db(appconfig):
under_test_real_database = bool(os.environ.get('TEST_DATABASE_URI'))
configure(appconfig)
model._basequery._lookup_team_roles()
model._basequery.get_public_repo_visibility()
model.log.get_log_entry_kinds()
if (not under_test_real_database):
db.obj.execut... |
(os.getuid(), 'test requires non-root access')
class FailsToOpenOutputFile_TestCase(TestCase):
def setUp(self):
self._include_path = mktempfile('text', prefix='ks-include')
ks_content = ('autopart\n%%include %s' % self._include_path)
self._ks_path = mktempfile(ks_content)
self._outpu... |
def test_makefile() -> None:
utils.print_title('Testing makefile')
a2x_path = (pathlib.Path(sys.executable).parent / 'a2x')
assert a2x_path.exists(), a2x_path
with tempfile.TemporaryDirectory() as tmpdir:
subprocess.run(['make', '-f', 'misc/Makefile', f'DESTDIR={tmpdir}', f'A2X={a2x_path}', 'ins... |
def find(root: (Path | str), dirs: bool=True) -> str:
if isinstance(root, str):
root = Path(root)
results: list[Path] = []
for (dirpath, dirnames, filenames) in os.walk(root):
names = filenames
if dirs:
names += dirnames
for name in names:
results.appe... |
def start_training():
logger.info('Setup config, data and model...')
opt = BaseOptions().parse()
set_seed(opt.seed)
if opt.debug:
cudnn.benchmark = False
cudnn.deterministic = True
dataset_config = dict(dset_name=opt.dset_name, data_path=opt.train_path, v_feat_dirs=opt.v_feat_dirs, q... |
def minmax(iterable_or_value, *others, key=None, default=_marker):
iterable = ((iterable_or_value, *others) if others else iterable_or_value)
it = iter(iterable)
try:
lo = hi = next(it)
except StopIteration as e:
if (default is _marker):
raise ValueError('`minmax()` argument ... |
class WorkuploadComFolder(SimpleDecrypter):
__name__ = 'WorkuploadComFolder'
__type__ = 'decrypter'
__version__ = '0.01'
__status__ = 'testing'
__pattern__ = '
__config__ = [('enabled', 'bool', 'Activated', True), ('use_premium', 'bool', 'Use premium account if available', True), ('folder_per_pa... |
def evolve_function_sig_callback(ctx: mypy.plugin.FunctionSigContext) -> CallableType:
if (len(ctx.args) != 2):
ctx.api.fail(f'"{ctx.default_signature.name}" has unexpected type annotation', ctx.context)
return ctx.default_signature
if (len(ctx.args[0]) != 1):
return ctx.default_signatur... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.