code stringlengths 281 23.7M |
|---|
class _PrimitiveTemplateBase(TypeTemplate):
public_proxy = ('encode', 'decode')
def __eq__(self, other):
return (type(self) is type(other))
def __hash__(self):
return hash(type(self))
def get_name(self):
return self.__class__.__name__[1:]
def get_kind(self):
return 'p... |
def iload_fh(f):
for (sc, cc, rcs) in parse3(f):
nslc = (pcode(get1(sc, b'16')), pcode(get1(sc, b'03')), ploc(get1(cc, b'03', b'')), pcode(get1(cc, b'04')))
try:
tmin = pdate(get1(cc, b'22'))
tmax = pdate(get1(cc, b'23'))
except util.TimeStrError as e:
rai... |
class SimCLR(object):
def __init__(self, config):
self.config = config
self.device = self._get_device()
self.writer = SummaryWriter(os.path.join(self.config['save_dir'], 'tensorboard'))
self.nt_xent_criterion = NTXentLoss(self.device, **config['loss'])
split_dir = os.path.joi... |
def open_frag_dbs(databases_options):
databases = databases_options.databases
if (not databases):
raise click.BadArgumentUsage('must specify at least one fragment database')
if (len(databases) == 1):
return SingleDatabase(databases[0])
else:
return MultipleDatabases(databases) |
def test_permutation_generator():
perms = generate_permutations(3)
assert (len(perms) == 2)
assert (perms[0] == [0, 1, 2])
assert (perms[1] == [1, 2, 0])
perms = generate_permutations(4)
assert (len(perms) == 2)
assert (perms[0] == [0, 1, 2, 3])
assert (perms[1] == [1, 3, 0, 2])
perm... |
class QiskitNatureLogging():
LOG_FORMAT = '%(asctime)s:%(name)s:%(levelname)s: %(message)s'
def get_levels_for_names(self, names: List[str]) -> Dict[(str, int)]:
name_levels: Dict[(str, int)] = {}
for name in names:
name_levels[name] = python_logging.getLogger(name).getEffectiveLevel... |
def run_tests():
excludes = []
suite = unittest.TestSuite()
sys.path.append(testfolder)
for (root, dirs, files) in os.walk(testfolder):
test_modules = [file.replace('.py', '') for file in files if (file.startswith('test_') and file.endswith('.py'))]
test_modules = [mod for mod in test_mo... |
def backward_G(args, G_target, D_target, gen_in):
if args.miner:
gen_in = miner(gen_in)
fake_image_tgt = G_target(gen_in, step=step, alpha=alpha)
predict = D_target(fake_image_tgt, step=step, alpha=alpha)
gen_loss = F.softplus((- predict)).mean()
if (args.lambda_l2_G > 0):
l2_G_loss ... |
_fixtures(WebFixture, FormLayoutFixture)
def test_adding_basic_input(web_fixture, form_layout_fixture):
fixture = form_layout_fixture
class FormWithInputAddedUsingDefaults(Form):
def __init__(self, view):
super().__init__(view, 'aform')
self.use_layout(FormLayout())
s... |
def events_for_expired_withdraws(channel_state: NettingChannelState, block_number: BlockNumber, pseudo_random_generator: random.Random) -> List[SendWithdrawExpired]:
events: List[SendWithdrawExpired] = []
for withdraw_state in list(channel_state.our_state.withdraws_pending.values()):
withdraw_expired = ... |
def _get_format_filter(format_name: str, checker: jsonschema.FormatChecker, strategy: st.SearchStrategy[str]) -> st.SearchStrategy[str]:
def check_valid(string: str) -> str:
try:
if (not isinstance(string, str)):
raise jsonschema.exceptions.FormatError(f'{string!r} is not a strin... |
class TestBasicsXarray(TestBasics):
def setup_method(self):
reload(pysat.instruments.pysat_testing_xarray)
self.testInst = pysat.Instrument(platform='pysat', name='testing_xarray', num_samples=10, clean_level='clean', update_files=True, use_header=True, **self.testing_kwargs)
self.ref_time =... |
def reduce_process(opts, output_queue, spool_length, out_file=None, file_size=0, file_compress=True):
global options
options = opts
createLogger(options.quiet, options.debug, options.log_file)
if out_file:
nextFile = NextFile(out_file)
output = OutputSplitter(nextFile, file_size, file_co... |
class BaseNodeVisitorTester(object):
visitor_cls = None
def _run_str(self, code_str, expect_failure=False, apply_changes=False, **kwargs):
kwargs.setdefault('fail_after_first', (not apply_changes))
if isinstance(code_str, bytes):
code_str = code_str.decode('utf-8')
code_str =... |
class IsolatedEnv(BaseIsolatedEnv):
def __init__(self, env: Env, pool: RepositoryPool) -> None:
self._env = env
self._pool = pool
def python_executable(self) -> str:
return str(self._env.python)
def make_extra_environ(self) -> dict[(str, str)]:
path = os.environ.get('PATH')
... |
('I assign {value_str} to table.alignment')
def when_I_assign_value_to_table_alignment(context, value_str):
value = {'None': None, 'WD_TABLE_ALIGNMENT.LEFT': WD_TABLE_ALIGNMENT.LEFT, 'WD_TABLE_ALIGNMENT.RIGHT': WD_TABLE_ALIGNMENT.RIGHT, 'WD_TABLE_ALIGNMENT.CENTER': WD_TABLE_ALIGNMENT.CENTER}[value_str]
table = ... |
class Address(Base):
__tablename__ = 'datatablebootstrap_address'
id = Column(Integer, primary_key=True)
email_address = Column(UnicodeText)
name = Column(UnicodeText)
zip_code = Column(Integer)
fields = ExposedNames()
fields.name = (lambda i: Field(label='Name', required=True))
fields.e... |
class QdrantUploader(BaseUploader):
client = None
upload_params = {}
def init_client(cls, host, distance, connection_params, upload_params):
os.environ['GRPC_ENABLE_FORK_SUPPORT'] = 'true'
os.environ['GRPC_POLL_STRATEGY'] = 'epoll,poll'
cls.client = QdrantClient(host=host, prefer_grp... |
class PinnaclePlan():
def __init__(self, pinnacle, path, plan):
self._pinnacle = pinnacle
self._path = path
self._plan_info = plan
self._machine_info = None
self._trials = None
self._trial_info = None
self._points = None
self._patient_setup = None
... |
def assert_envelope_values(nonce: int, channel_identifier: ChannelID, transferred_amount: TokenAmount, locked_amount: LockedAmount, locksroot: Locksroot) -> None:
if (nonce <= 0):
raise ValueError('nonce cannot be zero or negative')
if (nonce > UINT64_MAX):
raise ValueError('nonce is too large')... |
class TestDundersFullOrdering():
cls = FullOrderCSameType
def test_class(self):
assert (self.cls.__name__ == 'FullOrderCSameType')
assert (self.cls.__qualname__ == 'FullOrderCSameType')
def test_eq(self):
method = self.cls.__eq__
assert (method.__doc__.strip() == 'Return a ==... |
def create_argparser():
defaults = dict(clip_denoised=True, num_samples=10000, batch_size=16, use_ddim=False, model_path='', classifier_path='', classifier_scale=1.0, img_size=224)
defaults.update(model_and_diffusion_defaults())
defaults.update(classifier_defaults())
parser = argparse.ArgumentParser()
... |
def evaluate(model, dataset, device, filename):
print('Start the evaluation')
model.eval()
(image, mask, gt) = zip(*[dataset[i] for i in range(8)])
image = torch.stack(image)
mask = torch.stack(mask)
gt = torch.stack(gt)
with torch.no_grad():
(output, _) = model(image.to(device), mas... |
class TestTrackingDict():
def test_slot_behaviour(self, td):
for attr in td.__slots__:
assert (getattr(td, attr, 'err') != 'err'), f"got extra slot '{attr}'"
assert (len(mro_slots(td)) == len(set(mro_slots(td)))), 'duplicate slot'
def test_representations(self, td, data):
ass... |
_handler('bookmarks')
def qute_bookmarks(_url: QUrl) -> _HandlerRet:
bookmarks = sorted(objreg.get('bookmark-manager').marks.items(), key=(lambda x: x[1]))
quickmarks = sorted(objreg.get('quickmark-manager').marks.items(), key=(lambda x: x[0]))
src = jinja.render('bookmarks.html', title='Bookmarks', bookmar... |
def test_complete_set_value_invalid_settable(cmd2_app, capsys):
text = ''
line = 'set fake {}'.format(text)
endidx = len(line)
begidx = (endidx - len(text))
first_match = complete_tester(text, line, begidx, endidx, cmd2_app)
assert (first_match is None)
(out, err) = capsys.readouterr()
a... |
def main(args):
text = codecs.open(Path(args.in_path), 'r', 'utf-8')
spk2textgrid = {}
xmin = 0
xmax = 0
for line in text:
uttlist = line.split()
utt_id = uttlist[0]
if ((utt_id == '') or (utt_id == '')):
continue
utt_text = uttlist[1]
utt_use = ut... |
def unify_generic_callable(type: NormalizedCallableType, target: NormalizedCallableType, ignore_return: bool, return_constraint_direction: (int | None)=None, *, no_unify_none: bool=False) -> (NormalizedCallableType | None):
import mypy.solve
if (return_constraint_direction is None):
return_constraint_di... |
def set_freeze_by_names(model, layer_alias=None, layer_names=None, freeze=True):
if ((layer_names is None) and (layer_alias is not None)):
(layer_names, name_alias_map) = get_actual_layer_names(model, layer_alias)
elif ((layer_names is None) and (layer_alias is None)):
logging.info(f'No layer_na... |
class ParserElement(object):
DEFAULT_WHITE_CHARS = ' \n\t\r'
verbose_stacktrace = False
def setDefaultWhitespaceChars(chars):
ParserElement.DEFAULT_WHITE_CHARS = chars
for expr in _builtin_exprs:
if expr.copyDefaultWhiteChars:
expr.whiteChars = chars
def inlin... |
def logging_set(output_dir):
logging.basicConfig(filename=os.path.join(output_dir, 'train_{}.log'.format(datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))), format='%(message)s')
logger = logging.getLogger()
logger.setLevel(logging.INFO)
console = logging.StreamHandler()
logging.getLogger('').a... |
(scope='function')
def tiffs(tmpdir):
with rasterio.open('tests/data/RGB.byte.tif') as src:
profile = src.profile
shadowed_profile = profile.copy()
shadowed_profile['count'] = 4
with rasterio.open(str(tmpdir.join('shadowed.tif')), 'w', **shadowed_profile) as dst:
for (i, ... |
def print_client_info(disp, client):
print('client: {}'.format(client))
resources = disp.res_query_client_resources(client)
rc = [r.count for r in resources.types]
print('\tresouces: {} resources of {} types'.format(sum(rc), len(rc)))
pb = disp.res_query_client_pixmap_bytes(client)
print('\tpixm... |
class AnyStage(nn.Sequential):
def __init__(self, width_in: int, width_out: int, stride: int, depth: int, block_constructor: nn.Module, activation: nn.Module, bot_mul: float, group_width: int, params: 'RegNetParams', stage_index: int=0):
super().__init__()
self.stage_depth = 0
for i in range... |
def patch_messages():
old_add_message = PyLinter.add_message
def new_add_message(self, msg_id, line=None, node=None, args=None, confidence=UNDEFINED, col_offset=None, end_lineno=None, end_col_offset=None):
old_add_message(self, msg_id, line, node, args, confidence, col_offset, end_lineno, end_col_offset... |
class MIPSLexer(RegexLexer):
name = 'MIPS'
aliases = ['mips']
version_added = ''
filenames = ['*.mips', '*.MIPS']
url = '
keywords = ['add', 'sub', 'subu', 'addi', 'subi', 'addu', 'addiu', 'mul', 'mult', 'multu', 'mulu', 'madd', 'maddu', 'msub', 'msubu', 'div', 'divu', 'and', 'or', 'nor', 'xor',... |
class DatasetImage(Dataset):
def __init__(self, data_dir, transform=transform_train, is_test=False, is_multi=False, tensor_norm=False):
self.data_dir = data_dir
self.paths = glob.glob(f'{data_dir}/**/*.jpg')
self.paths += glob.glob(f'{data_dir}/**/*.jpeg')
self.paths += glob.glob(f'{... |
class PTBInput(object):
def __init__(self, batch_size, num_steps, data, name=None):
self.batch_size = batch_size
self.num_steps = num_steps
self.epoch_size = (((len(data) // batch_size) - 1) // num_steps)
self.data_queue = reader.ptb_producer(data, batch_size, num_steps, name=name) |
class FlaubertOnnxConfig(OnnxConfig):
def inputs(self) -> Mapping[(str, Mapping[(int, str)])]:
if (self.task == 'multiple-choice'):
dynamic_axis = {0: 'batch', 1: 'choice', 2: 'sequence'}
else:
dynamic_axis = {0: 'batch', 1: 'sequence'}
return OrderedDict([('input_ids... |
(cc=STDCALL, params={'uFormat': UINT})
def hook_GetClipboardData(ql: Qiling, address: int, params):
uFormat = params['uFormat']
data = ql.os.clipboard.get_data(uFormat)
if data:
addr = ql.os.heap.alloc(len(data))
ql.mem.write(addr, data)
else:
ql.log.debug(f'Failed to get clipboa... |
def get_max_combination(list_of_extracted_meta, expected_meta_form):
total_rules = list(range(len(list_of_extracted_meta)))
mid_training_label = ([0] * len(list_of_extracted_meta))
max_match_extracted = set()
max_match_percent = 0
for i in range(1, 3):
all_combinations = list(itertools.combi... |
class AFileManager(AObject):
def AOBJECT_TYPE():
return 'AFileManager'
def getJSONPath(self):
return self.getPath()
def __init__(self, path=None, clear_temp=None):
AObject.__init__(self, path=path)
self.initWithPath(path=path, clear_temp=clear_temp)
def initializeBlank(se... |
class MoonshotSlippageTestCase(unittest.TestCase):
def tearDown(self):
for file in glob.glob('{0}/moonshot*.pkl'.format(TMP_DIR)):
os.remove(file)
def test_no_slippage(self):
class BuyBelow10ShortAbove10(Moonshot):
def prices_to_signals(self, prices):
long... |
def test_sqliteio_write_inserts_new_pixmap_item_without_filename(tmpfile, view, item):
view.scene.addItem(item)
io = SQLiteIO(tmpfile, view.scene, create_new=True)
io.write()
assert (item.save_id == 1)
result = io.fetchone('SELECT items.data, sqlar.name FROM items INNER JOIN sqlar on sqlar.item_id =... |
.parametrize('retriever, documents, k', [pytest.param(retriever, documents(), k, id=f'retriever: {retriever.__class__.__name__}, k: {k}') for k in [None, 2, 4] for retriever in cherche_retrievers(on='article')])
def test_retriever(retriever, documents: list, k: int):
retriever = (retriever + documents)
retrieve... |
((torch.__version__ < '1.6.0'), JIT_MSG)
class TestJitSequenceGenerator(TestJitSequenceGeneratorBase):
def test_export_transformer(self):
model = self.transformer_model
torch.jit.script(model)
def test_ensemble_sequence_generator(self):
model = self.transformer_model
generator = ... |
def test_poly_union():
with pytest.raises(AssertionError):
utils.poly_union(0, 1)
points = [0, 0, 0, 1, 1, 1, 1, 0]
points1 = [2, 2, 2, 3, 3, 3, 3, 2]
points2 = [0, 0, 0, 0, 0, 0, 0, 0]
points3 = [0, 0, 0, 1, 1, 0, 1, 1]
points4 = [0.5, 0.5, 1, 0, 1, 1, 0.5, 0.5]
poly = utils.points2... |
def main():
cfg = Config()
cfg = parse_cmdline_args_to_config(cfg)
if ('CUDA_VISIBLE_DEVICES' not in os.environ):
os.environ['CUDA_VISIBLE_DEVICES'] = cfg.available_gpus
log_config(cfg)
if (cfg.task == 'video'):
generate_video(cfg)
elif (cfg.task == 'video_interp'):
inter... |
class Vox256_cross(Dataset):
def __init__(self, transform=None):
self.ds_path = './datasets/vox/test/'
self.videos = os.listdir(self.ds_path)
self.anno = pd.read_csv('pairs_annotations/vox256.csv')
self.transform = transform
def __getitem__(self, idx):
source_name = self.... |
_test
def test_conv1d_legacy_interface():
old_layer = keras.layers.Convolution1D(5, filter_length=3, input_dim=3, input_length=4, name='conv')
new_layer = keras.layers.Conv1D(5, 3, name='conv', input_shape=(4, 3))
assert (json.dumps(old_layer.get_config()) == json.dumps(new_layer.get_config()))
old_laye... |
_required
_
def proposal_upload_content(request, conference_slug, slug):
conference = get_object_or_404(Conference, slug=conference_slug)
proposal = get_object_or_404(Proposal, slug=slug, conference=conference)
if (not (permissions.is_proposal_section_reviewer(request.user, conference, proposal) or request.... |
class XML(XHTML):
newline_default_on = set()
def _stringify(self, str_type):
join = ('\n' if self._newlines else '')
if (self._name is None):
return join.join(map(str_type, self._content))
a = [('%s="%s"' % i) for i in self._attrs.items()]
l = ([self._name] + a)
... |
def _to_list(results):
for img_id in results:
for t in range(len(results[img_id])):
for k in results[img_id][t]:
if isinstance(results[img_id][t][k], (np.ndarray, np.float32)):
results[img_id][t][k] = results[img_id][t][k].tolist()
return results |
class Migration(migrations.Migration):
dependencies = [('conferences', '0028_store_incoming_webhooks_in_conference_model'), ('submissions', '0019_allow_adding_a_short_summy_for_socials')]
operations = [migrations.AlterField(model_name='submission', name='topic', field=models.ForeignKey(null=True, blank=True, on... |
class SamplerFactory():
def __init__(self):
pass
def get_by_name(dataset_name, dataset):
if (dataset_name == 'Mixed_EXPR'):
from .imbalanced_SLML import ImbalancedDatasetSampler_SLML
sampler = ImbalancedDatasetSampler_SLML(dataset)
elif (dataset_name == 'Mixed_AU'... |
class LocalPath():
class ImportMismatchError(ImportError):
sep = os.sep
def __init__(self, path=None, expanduser=False):
if (path is None):
self.strpath = error.checked_call(os.getcwd)
else:
try:
path = os.fspath(path)
except TypeError:
... |
_error_logging()
class CurrentPositionsSheet(AbstractDocument):
def __init__(self, settings: Settings, pdf_exporter: PDFExporter, portfolio: Portfolio, title: str='Current Positions'):
super().__init__(settings, pdf_exporter, title)
self._portfolio = portfolio
def build_document(self):
s... |
class STM32F1xxRcc(QlPeripheral):
class Type(ctypes.Structure):
_fields_ = [('CR', ctypes.c_uint32), ('CFGR', ctypes.c_uint32), ('CIR', ctypes.c_uint32), ('APB2RSTR', ctypes.c_uint32), ('APB1RSTR', ctypes.c_uint32), ('AHBENR', ctypes.c_uint32), ('APB2ENR', ctypes.c_uint32), ('APB1ENR', ctypes.c_uint32), ('B... |
class TestDrudeLorentzBath():
def test_create(self):
Q = sigmaz()
ck_real = [0., 0.]
vk_real = [0.05, 6.]
ck_imag = [(- 0.)]
vk_imag = [0.05]
bath = DrudeLorentzBath(Q=Q, lam=0.025, T=(1 / 0.95), Nk=1, gamma=0.05, tag='bath1')
[exp1, exp2] = bath.exponents
... |
def commands_normalize_resnet(resnet_features_dir: str=RESNET_FEATURES_DIR, resnet_normalized_features_dir: str=RESNET_NORMALIZED_FEATURES_DIR, models_dir: str=MODELS_DIR, splits_dir: str=SPLITS_DIR) -> List[Command]:
normalizer_path = os.path.join(models_dir, RESNET_NORMALIZER_PKL)
create_normalizer_command = ... |
def subfiles(folder, join=True, prefix=None, suffix=None, sort=True):
if join:
l = os.path.join
else:
l = (lambda x, y: y)
res = [l(folder, i) for i in os.listdir(folder) if (os.path.isfile(os.path.join(folder, i)) and ((prefix is None) or i.startswith(prefix)) and ((suffix is None) or i.end... |
class Tenum(TestCase):
def test_enum(self):
class Foo(object):
FOO = 1
BAR = 3
self.assertEqual(Foo.FOO, 1)
self.assertTrue(isinstance(Foo.FOO, Foo))
self.assertEqual(repr(Foo.FOO), '<Foo.FOO: 1>')
self.assertEqual(repr(Foo(3)), '<Foo.BAR: 3>')
... |
class SupervisedGraphsage(models.SampleAndAggregate):
def __init__(self, placeholders, features, layer_infos, batch_size=32, concat=True, aggregator_type='mean', model_size='small', name=None, **kwargs):
models.GeneralizedModel.__init__(self, **kwargs)
if (aggregator_type == 'mean'):
sel... |
class PartialParquetParameters(PartialFileDownloadParams):
def of(row_groups_to_download: Optional[List[int]]=None, num_row_groups: Optional[int]=None, num_rows: Optional[int]=None, in_memory_size_bytes: Optional[float]=None, pq_metadata: Optional[FileMetaData]=None) -> PartialParquetParameters:
if ((row_gr... |
class JciHitachiPowerConsumptionSensorEntity(JciHitachiEntity, SensorEntity):
def __init__(self, thing, coordinator):
super().__init__(thing, coordinator)
def name(self):
return f'{self._thing.name} Power Consumption'
def native_value(self):
status = self.hass.data[DOMAIN][UPDATED_DA... |
_platform(Platform.WINDOWS)
class WindowsMulticoreClockTestCase(unittest.TestCase):
def test_multicore(self):
failures = 0
old_time = clock()
end_time = (time.time() + 3)
while (time.time() < end_time):
t = clock()
if (t < old_time):
failures +... |
class Adaround():
def apply_adaround(cls, session: tf.compat.v1.Session, starting_op_names: List[str], output_op_names: List[str], params: AdaroundParameters, path: str, filename_prefix: str, default_param_bw: int=4, default_quant_scheme: QuantScheme=QuantScheme.post_training_tf_enhanced, default_config_file: str=N... |
class GemmRelated(COp):
__props__: tuple[(str, ...)] = ()
def c_support_code(self, **kwargs):
mod_str = '\n #ifndef MOD\n #define MOD %\n #endif\n static double time_time() // a time function like time.perf_counter()\n {\n struct timeval tv;\n get... |
class TagTreeJoinUtilTest(TestCase):
def test_join_tree_none(self):
name = tag_utils.join_tree_name([])
self.assertEqual(name, '')
def test_join_tree_one(self):
name = tag_utils.join_tree_name(['one'])
self.assertEqual(name, 'one')
def test_join_tree_three(self):
name... |
def _container_getitem(instance, elts, index, context: (InferenceContext | None)=None):
try:
if isinstance(index, Slice):
index_slice = _infer_slice(index, context=context)
new_cls = instance.__class__()
new_cls.elts = elts[index_slice]
new_cls.parent = instan... |
class ChannelListView(ChannelMixin, ListView):
paginate_by = 100
template_name = 'website/channel_list.html'
page_title = 'Channel Index'
max_popular = 10
def get_context_data(self, **kwargs):
context = super(ChannelListView, self).get_context_data(**kwargs)
context['most_popular'] =... |
class CSHintDetailsTab(GameDetailsTab):
def __init__(self, parent: QtWidgets.QWidget, game: RandovaniaGame):
super().__init__(parent, game)
self.tree_widget = QtWidgets.QTreeWidget(parent)
def widget(self) -> QtWidgets.QWidget:
return self.tree_widget
def tab_title(self) -> str:
... |
class FakeFilesystem():
def __init__(self, path_separator: str=os.path.sep, total_size: Optional[int]=None, patcher: Any=None, create_temp_dir: bool=False) -> None:
self.path_separator: str = path_separator
self.alternative_path_separator: Optional[str] = os.path.altsep
self.patcher = patche... |
class ApiException(HTTPException):
def __init__(self, error_type, status_code, error_description, payload=None):
Exception.__init__(self)
self.error_description = error_description
self.code = status_code
self.payload = payload
self.error_type = error_type
self.data =... |
class RCC_APB1ENR(IntEnum):
TIM2EN = (1 << 0)
TIM3EN = (1 << 1)
TIM4EN = (1 << 2)
TIM5EN = (1 << 3)
WWDGEN = (1 << 11)
SPI2EN = (1 << 14)
SPI3EN = (1 << 15)
USART2EN = (1 << 17)
I2C1EN = (1 << 21)
I2C2EN = (1 << 22)
I2C3EN = (1 << 23)
PWREN = (1 << 28) |
def match_script_against_template(script, template) -> bool:
if (script is None):
return False
if isinstance(script, (bytes, bytearray)):
try:
script = [x for x in script_GetOp(script)]
except MalformedBitcoinScript:
return False
if (len(script) != len(templat... |
.parametrize('exc_cls', (BaseException, Exception, GeneratorExit, KeyboardInterrupt, RuntimeError, SystemExit))
def test_instance_method_spy_exception(exc_cls: Type[BaseException], mocker: MockerFixture) -> None:
class Foo():
def bar(self, arg):
raise exc_cls(f'Error with {arg}')
foo = Foo()... |
def notify_new_submission(submission_id: int, title: str, elevator_pitch: str, submission_type: str, admin_url: str, duration: int, topic: str, speaker_id: int, conference_id: int, tags: str):
publish_message('NewCFPSubmission', {'title': title, 'elevator_pitch': elevator_pitch, 'submission_type': submission_type, ... |
def calculate_max_pss_salt_length(key: (rsa.RSAPrivateKey | rsa.RSAPublicKey), hash_algorithm: hashes.HashAlgorithm) -> int:
if (not isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey))):
raise TypeError('key must be an RSA public or private key')
emlen = ((key.key_size + 6) // 8)
salt_length = ((... |
def local_to_utc(df):
try:
offset_hour = (- (datetime.now() - datetime.utcnow()).seconds)
except:
offset_hour = (time.altzone if time.daylight else time.timezone)
offset_hour = (offset_hour // 3600)
offset_hour = (offset_hour if (offset_hour < 10) else (offset_hour // 10))
df = df.co... |
def _multi_create_fileset(base_dir, name, structure, recurse):
range_count = structure.get('range')
if range_count:
if isinstance(range_count, int):
range_count = [range_count]
for count in range(*range_count):
_create_fileset(os.path.join(base_dir, name.format(count)), s... |
def CollateIterators(*rorp_iters):
iter_num = len(rorp_iters)
if (iter_num == 2):
return Collate2Iters(rorp_iters[0], rorp_iters[1])
overflow = ([None] * iter_num)
rorps = overflow[:]
def setrorps(overflow, rorps):
for i in range(iter_num):
if ((not overflow[i]) and (rorp... |
_on_pypy
def test_dynamic_attributes():
instance = m.DynamicClass()
assert (not hasattr(instance, 'foo'))
assert ('foo' not in dir(instance))
instance.foo = 42
assert hasattr(instance, 'foo')
assert (instance.foo == 42)
assert ('foo' in dir(instance))
assert ('foo' in instance.__dict__)
... |
def parse_args():
parser = argparse.ArgumentParser(description='Simple example of a training script.')
parser.add_argument('--filepath', type=str, help='path of the model')
parser.add_argument('--max_train_steps', type=int, default=1000, help='Total number of training steps to perform. If provided, overrid... |
def format_list(lst: Sequence[str], style: Literal[('standard', 'standard-short', 'or', 'or-short', 'unit', 'unit-short', 'unit-narrow')]='standard', locale: ((Locale | str) | None)=DEFAULT_LOCALE) -> str:
locale = Locale.parse(locale)
if (not lst):
return ''
if (len(lst) == 1):
return lst[0... |
class CodeBlock(Block):
accepts_lines = True
def continue_(parser=None, container=None):
ln = parser.current_line
indent = parser.indent
if container.is_fenced:
match = ((indent <= 3) and (len(ln) >= (parser.next_nonspace + 1)) and (ln[parser.next_nonspace] == container.fence... |
class ControlStateTests(unittest.TestCase):
def setUp(self):
self.app = Application()
self.app.start(os.path.join(mfc_samples_folder, u'CmnCtrl1.exe'))
self.dlg = self.app.Common_Controls_Sample
self.dlg.TabControl.select(4)
self.ctrl = self.dlg.EditBox.find()
def tearDow... |
def load_sem_seg(gt_root, image_root, gt_ext='png', image_ext='jpg'):
def file2id(folder_path, file_path):
image_id = os.path.normpath(os.path.relpath(file_path, start=folder_path))
image_id = os.path.splitext(image_id)[0]
return image_id
input_files = sorted((os.path.join(image_root, f)... |
class _PlainFormatter():
_error_format = field()
def filenotfound_error(self, path, exc_info):
return '{!r} does not exist.\n'.format(path)
def parsing_error(self, path, exc_info):
return 'Failed to parse {}: {}\n'.format(('<stdin>' if (path == '<stdin>') else repr(path)), exc_info[1])
d... |
class HugefilesNet(XFSDownloader):
__name__ = 'HugefilesNet'
__type__ = 'downloader'
__version__ = '0.12'
__status__ = 'testing'
__pattern__ = '
__config__ = [('enabled', 'bool', 'Activated', True), ('use_premium', 'bool', 'Use premium account if available', True), ('fallback', 'bool', 'Fallback... |
class QtPluginBase(object):
def load_wallet(self: Union[('QtPluginBase', HW_PluginBase)], wallet: 'Abstract_Wallet', window: ElectrumWindow):
relevant_keystores = [keystore for keystore in wallet.get_keystores() if isinstance(keystore, self.keystore_class)]
if (not relevant_keystores):
r... |
def receptive_field(net):
def _f(output_size, ksize, stride, dilation):
return (((((output_size - 1) * stride) + (ksize * dilation)) - dilation) + 1)
stats = []
for m in net.modules():
if isinstance(m, (nn.Conv2d, nn.AvgPool2d, nn.MaxPool2d)):
stats.append((m.kernel_size, m.strid... |
class SarlLexer(RegexLexer):
name = 'SARL'
url = '
aliases = ['sarl']
filenames = ['*.sarl']
mimetypes = ['text/x-sarl']
version_added = '2.4'
flags = (re.MULTILINE | re.DOTALL)
tokens = {'root': [('^(\\s*(?:[a-zA-Z_][\\w.\\[\\]]*\\s+)+?)([a-zA-Z_$][\\w$]*)(\\s*)(\\()', bygroups(using(th... |
def test_make_setup_py_reqs():
builder = sdist.SdistBuilder.from_ini_path(((samples_dir / 'extras') / 'pyproject.toml'))
ns = get_setup_assigns(builder.make_setup_py())
assert (ns['install_requires'] == ['toml'])
assert (ns['extras_require'] == {'test': ['pytest'], 'custom': ['requests']}) |
class GetChatMember():
async def get_chat_member(self: 'pyrogram.Client', chat_id: Union[(int, str)], user_id: Union[(int, str)]) -> 'types.ChatMember':
chat = (await self.resolve_peer(chat_id))
user = (await self.resolve_peer(user_id))
if isinstance(chat, raw.types.InputPeerChat):
... |
.parametrize('voucher_tag,voucher_code,expected_roles', (('speakers', 'code', [Role.SPEAKER, Role.ATTENDEE]), ('', 'keynoter-123', [Role.KEYNOTER, Role.ATTENDEE]), ('staff', 'code', [Role.STAFF, Role.ATTENDEE]), ('', 'staff-5667', [Role.STAFF, Role.ATTENDEE]), ('sponsor,pizzacorp', 'pizza', [Role.SPONSOR, Role.ATTENDEE... |
def bin_encode_attr(attr: Dict[(str, Any)]) -> None:
if (BINARY in attr):
attr[BINARY] = _b64encode(attr[BINARY])
elif (BINARY_SET in attr):
attr[BINARY_SET] = [_b64encode(v) for v in attr[BINARY_SET]]
elif (MAP in attr):
for sub_attr in attr[MAP].values():
bin_encode_att... |
class testMiscIters(unittest.TestCase):
def setUp(self):
Myrm(abs_output_dir)
self.outputrp = rpath.RPath(Globals.local_connection, abs_output_dir)
self.regfile1 = self.outputrp.append('reg1')
self.regfile2 = self.outputrp.append('reg2')
self.regfile3 = self.outputrp.append('... |
def test_merge_into_using_subquery():
sql = 'MERGE INTO target USING (select k, max(v) as v_max from src group by k) AS b ON target.k = b.k\nWHEN MATCHED THEN UPDATE SET target.v = b.v_max\nWHEN NOT MATCHED THEN INSERT (k, v) VALUES (b.k, b.v_max)'
assert_column_lineage_equal(sql, [(ColumnQualifierTuple('v', 's... |
class GELUActivation(nn.Module):
def __init__(self, use_gelu_python: bool=False):
super().__init__()
if ((version.parse(version.parse(torch.__version__).base_version) < version.parse('1.4')) or use_gelu_python):
self.act = self._gelu_python
else:
self.act = nn.functio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.