code stringlengths 281 23.7M |
|---|
class ResNetBasicLayer(nn.Module):
def __init__(self, in_channels: int, out_channels: int, stride: int=1, activation: str='relu'):
super().__init__()
should_apply_shortcut = ((in_channels != out_channels) or (stride != 1))
self.shortcut = (ResNetShortCut(in_channels, out_channels, stride=str... |
def test_pytest_exit_returncode(pytester: Pytester) -> None:
pytester.makepyfile(' import pytest\n def test_foo():\n pytest.exit("some exit msg", 99)\n ')
result = pytester.runpytest()
result.stdout.fnmatch_lines(['*! *Exit: some exit msg !*'])
assert (_strip_resource_warning... |
_bool('is_required_a', 'is_required_b', 'is_required_c', 'is_required_d')
def test_several_extra_target(debug_ctx, debug_trail, trail_select, is_required_a, is_required_b, is_required_c, is_required_d, acc_schema):
dumper_getter = make_dumper_getter(shape=shape(TestField('a', acc_schema.accessor_maker('a', is_requi... |
def _harmonic_oscillator_spectrum_frequency(n_th, w0, kappa):
if (n_th == 0):
return (lambda w: (kappa * (w >= 0)))
w_th = (w0 / np.log((1 + (1 / n_th))))
def f(t, w):
scale = (np.exp((w / w_th)) if (w < 0) else 1)
return (((n_th + 1) * kappa) * scale)
return f |
def adjust_learning_rate(lr_scheduler: Union[(optim.lr_scheduler.StepLR, optim.lr_scheduler.ReduceLROnPlateau)], epoch: int, train_loss: float, dev_f1: float) -> bool:
if isinstance(lr_scheduler, optim.lr_scheduler.StepLR):
if isinstance(lr_scheduler.optimizer, AdaBound):
lr_scheduler.step()
... |
def FCN_aspp(img_shape, class_n=None):
input_shape = (None, img_shape[0], img_shape[1], img_shape[2], 1)
input_img = Input(shape=input_shape[1:])
conv1_1 = Conv3D(32, 3, padding='same', activation='relu')(input_img)
conv1_2 = Conv3D(32, 3, padding='same', activation='relu')(conv1_1)
pool1 = MaxPooli... |
class CholeskySolve(SolveBase):
def __init__(self, **kwargs):
kwargs.setdefault('lower', True)
super().__init__(**kwargs)
def perform(self, node, inputs, output_storage):
(C, b) = inputs
rval = scipy.linalg.cho_solve((C, self.lower), b, check_finite=self.check_finite)
out... |
def _gen_efficientnet(variant, channel_multiplier=1.0, depth_multiplier=1.0, pretrained=False, **kwargs):
arch_def = [['ds_r1_k3_s1_e1_c16_se0.25'], ['ir_r2_k3_s2_e6_c24_se0.25'], ['ir_r2_k5_s2_e6_c40_se0.25'], ['ir_r3_k3_s2_e6_c80_se0.25'], ['ir_r3_k5_s1_e6_c112_se0.25'], ['ir_r4_k5_s2_e6_c192_se0.25'], ['ir_r1_k3... |
class _TestResult(TestResult):
def __init__(self, verbosity=1):
TestResult.__init__(self)
self.stdout0 = None
self.stderr0 = None
self.success_count = 0
self.failure_count = 0
self.error_count = 0
self.verbosity = verbosity
self.result = []
def sta... |
class PassThroughOptionParser(OptionParser):
def _process_args(self, largs, rargs, values):
while rargs:
try:
OptionParser._process_args(self, largs, rargs, values)
except (BadOptionError, AmbiguousOptionError) as e:
largs.append(e.opt_str) |
class CopyProcessor(BaseProcessor):
def __init__(self, config, *args, **kwargs):
self.max_length = config.max_length
def __call__(self, item):
blob = item['blob']
final_blob = np.zeros(((self.max_length,) + blob.shape[1:]), blob.dtype)
final_blob[:len(blob)] = blob[:len(final_blo... |
def convert_requirements(requirements: list[str]) -> Iterator[str]:
for req in requirements:
parsed_requirement = Requirement(req)
spec = requires_to_requires_dist(parsed_requirement)
extras = ','.join(sorted((safe_extra(e) for e in parsed_requirement.extras)))
if extras:
... |
class RedshiftDatasource(Datasource[Union[(ArrowRow, Any)]]):
def prepare_read(self, parallelism: int, paths: Union[(str, List[str])], content_type_provider: Callable[([str], ContentType)], path_type: S3PathType=S3PathType.MANIFEST, filesystem: Optional[Union[(S3FileSystem, s3fs.S3FileSystem)]]=None, columns: Optio... |
class ConfigSource():
def __init__(self, root_path):
self.root_path = root_path
self.is_windows = (sys.platform == 'win32')
self.xdg_home = os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))
def user_config(self):
raise NotImplementedError()
def project_config... |
class CloudCompositorCommonMask(SingleBandCompositor):
def __call__(self, projectables, **info):
if (len(projectables) != 2):
raise ValueError(('Expected 2 datasets, got %d' % (len(projectables),)))
(data, cma) = projectables
valid_cma = (cma != cma.attrs['_FillValue'])
v... |
class VTM(Codec):
fmt = '.bin'
def description(self):
return 'VTM'
def name(self):
return 'VTM'
def setup_args(cls, parser):
super().setup_args(parser)
parser.add_argument('-b', '--build-dir', type=str, default='/home/felix/disk2/VVCSoftware_VTM/bin', help='VTM build dir'... |
class DigitalOceanOAuth(BaseOAuth2):
name = 'digitalocean'
AUTHORIZATION_URL = '
ACCESS_TOKEN_URL = '
ACCESS_TOKEN_METHOD = 'POST'
SCOPE_SEPARATOR = ' '
EXTRA_DATA = [('expires_in', 'expires_in')]
def get_user_id(self, details, response):
return response['account'].get('uuid')
de... |
_module()
class NerClassifier(BaseRecognizer):
def __init__(self, encoder, decoder, loss, label_convertor, train_cfg=None, test_cfg=None, init_cfg=None):
super().__init__(init_cfg=init_cfg)
self.label_convertor = build_convertor(label_convertor)
self.encoder = build_encoder(encoder)
... |
def touches(shape, other):
if (not hasattr(shape, GEO_INTERFACE_ATTR)):
raise TypeError((SHAPE_TYPE_ERR % shape))
if (not hasattr(other, GEO_INTERFACE_ATTR)):
raise TypeError((SHAPE_TYPE_ERR % shape))
o = geom.shape(shape)
o2 = geom.shape(other)
return o.touches(o2) |
class ConditionalDetrFeatureExtractor(ConditionalDetrImageProcessor):
def __init__(self, *args, **kwargs) -> None:
warnings.warn('The class ConditionalDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please use ConditionalDetrImageProcessor instead.', FutureWarning)
... |
def common_words(papers):
counter = Counter()
for paper in papers:
title = paper.lower()
splitted = title.split()
pos_word = nltk_posatg(splitted)
splitted = filter(pos_word)
counter.update(splitted)
keywords = []
for w in counter.most_common():
if (w[0] n... |
def monthly_heatmap(returns, benchmark=None, annot_size=10, figsize=(10, 5), cbar=True, square=False, returns_label='Strategy', compounded=True, eoy=False, grayscale=False, fontname='Arial', ylabel=True, savefig=None, show=True, active=False):
cmap = ('gray' if grayscale else 'RdYlGn')
returns = (_stats.monthly... |
def test_non_json_instance(run_line, tmp_path):
schema = (tmp_path / 'schema.json')
instance = (tmp_path / 'instance.json')
schema.write_text('{}')
instance.write_text('{')
res = run_line(['check-jsonschema', '--schemafile', str(schema), str(instance)])
assert (res.exit_code == 1)
assert (f'... |
class DescribeBaseOxmlElement():
def it_can_find_the_first_of_its_children_named_in_a_sequence(self, first_fixture):
(element, tagnames, matching_child) = first_fixture
assert (element.first_child_found_in(*tagnames) is matching_child)
def it_can_insert_an_element_before_named_successors(self, i... |
class PermutationRV(RandomVariable):
name = 'permutation'
ndim_supp = 1
ndims_params = [1]
dtype = None
_print_name = ('permutation', '\\operatorname{permutation}')
def rng_fn(cls, rng, x, size):
return rng.permutation(x)
def _supp_shape_from_params(self, dist_params, param_shapes=No... |
def get_pvc_info(name: str, namespace: str) -> PVC:
pvc_exists = check_if_pvc_exists(name=name, namespace=namespace)
if pvc_exists:
pvc_info_response = cli.read_namespaced_persistent_volume_claim(name=name, namespace=namespace, pretty=True)
pod_list_response = cli.list_namespaced_pod(namespace=n... |
class _CommandCfdSolver(CfdCommand):
def __init__(self):
super(_CommandCfdSolver, self).__init__()
self.resources = {'Pixmap': 'cfd-solver-standard', 'MenuText': QtCore.QT_TRANSLATE_NOOP('Cfd_Solver', 'Create CFD solver'), 'Accel': 'C, S', 'ToolTip': QtCore.QT_TRANSLATE_NOOP('Cfd_Solver', 'Create a ... |
class ItemAugInput(AugInput):
def __init__(self, image: np.ndarray, *, boxes=None, seg_info=None):
_check_img_dtype(image)
self.image = image
self.boxes = boxes
self.seg_info = seg_info
def transform(self, tfm: Transform) -> None:
self.image = tfm.apply_image(self.image)
... |
class FakeHistoryProgress():
def __init__(self, *, raise_on_tick=False):
self._started = False
self._finished = False
self._value = 0
self._raise_on_tick = raise_on_tick
def start(self, _text):
self._started = True
def set_maximum(self, _maximum):
pass
def... |
class TestReplyKeyboardMarkupWithoutRequest(TestReplyKeyboardMarkupBase):
def test_slot_behaviour(self, reply_keyboard_markup):
inst = reply_keyboard_markup
for attr in inst.__slots__:
assert (getattr(inst, attr, 'err') != 'err'), f"got extra slot '{attr}'"
assert (len(mro_slots(... |
class CaptionEntity(MessageFilter):
__slots__ = ('entity_type',)
def __init__(self, entity_type: str):
self.entity_type: str = entity_type
super().__init__(name=f'filters.CaptionEntity({self.entity_type})')
def filter(self, message: Message) -> bool:
return any(((entity.type == self.... |
class test_metrics(unittest.TestCase):
def setUp(self):
self.test = ['Oc1ccccc1-c1cccc2cnccc12', 'COc1cccc(NC(=O)Cc2coc3ccc(OC)cc23)c1']
self.test_sf = ['COCc1nnc(NC(=O)COc2ccc(C(C)(C)C)cc2)s1', 'O=C(C1CC2C=CC1C2)N1CCOc2ccccc21', 'Nc1c(Br)cccc1C(=O)Nc1ccncn1']
self.gen = ['CNC', 'Oc1ccccc1-c... |
class Bug(object):
def __init__(self, bugzilla, bug_id=None, dict=None, autorefresh=False):
self.bugzilla = bugzilla
self._rawdata = {}
self.autorefresh = autorefresh
self._aliases = self.bugzilla._get_bug_aliases()
if (not dict):
dict = {}
if bug_id:
... |
def test_coord_generator():
(i, j, k, l) = (0, 1, 2, 3)
true_set = {(i, j, k, l), (j, i, k, l), (i, j, l, k), (j, i, l, k), (k, l, i, j), (k, l, j, i), (l, k, i, j), (l, k, j, i)}
assert (true_set == set(_coord_generator(i, j, k, l)))
(i, j, k, l) = (1, 1, 2, 3)
true_set = {(i, j, k, l), (j, i, k, l... |
def set_model_weights_in_torch(weights, torch_model, hidden_size):
torch_model_reformer = torch_model.reformer
word_embeddings = np.asarray(weights[1])
set_param(torch_model_reformer.embeddings.word_embeddings, torch.tensor(word_embeddings))
if isinstance(weights[3], tuple):
position_embeddings ... |
def trainDataGenerator(batch_size, train_path, image_folder, mask_folder, aug_dict, image_color_mode='grayscale', mask_color_mode='grayscale', target_size=(256, 256), sal=False):
image_datagen = ImageDataGenerator(**aug_dict)
image_generator = image_datagen.flow_from_directory(train_path, classes=[image_folder]... |
('hash-set', [W_HashTable, values.W_Object, values.W_Object], simple=False)
def hash_set(table, key, val, env, cont):
from pycket.interpreter import return_value
if (not table.immutable()):
raise SchemeException('hash-set: not given an immutable table')
if isinstance(table, W_ImmutableHashTable):
... |
class SelfSubstitutionQuantifierEliminator(QuantifierEliminator, IdentityDagWalker):
LOGICS = [pysmt.logics.BOOL]
def __init__(self, environment, logic=None):
IdentityDagWalker.__init__(self, env=environment)
QuantifierEliminator.__init__(self)
self.logic = logic
def eliminate_quanti... |
def _decode_samples(data, image_key='jpg', image_format='RGB', target_key='cls', alt_label='', handler=log_and_continue):
for sample in data:
try:
result = _decode(sample, image_key=image_key, image_format=image_format, target_key=target_key, alt_label=alt_label)
except Exception as exn:... |
class BacktestMonitorSettings():
def __init__(self, issue_tearsheet=True, issue_portfolio_analysis_sheet=True, issue_trade_analysis_sheet=True, issue_transaction_log=True, issue_signal_log=True, issue_config_log=True, issue_daily_portfolio_values_file=True, print_stats_to_console=True, generate_pnl_chart_per_ticker... |
class CMDRegularizer(Regularizer):
def __init__(self, l=1.0, n_moments=5):
self.uses_learning_phase = 1
self.l = l
self.n_moments = n_moments
def set_layer(self, layer):
self.layer = layer
def __call__(self, loss):
if (not hasattr(self, 'layer')):
raise Ex... |
class ExpectationComputationalBasisStateTest(unittest.TestCase):
def test_expectation_fermion_operator_single_number_terms(self):
operator = (FermionOperator('3^ 3', 1.9) + FermionOperator('2^ 1'))
state = csc_matrix(([1], ([15], [0])), shape=(16, 1))
self.assertAlmostEqual(expectation_compu... |
def quantsim_custom_grad_learned_grid(inputs: tf.Tensor, encoding_min: tf.Variable, encoding_max: tf.Variable, op_mode: tf.Variable, bitwidth: tf.Variable, is_symmetric: tf.Variable, grad: tf.Tensor) -> Tuple[(tf.Variable, List[tf.Variable])]:
(dloss_by_dmin, dloss_by_dmax, dloss_by_dx) = _compute_dloss_by_dmin_dma... |
def build_dataset(args, rank=0, is_test=True):
tok = get_tokenizer(args)
feat_db = ImageFeaturesDB(args.img_ft_file, args.image_feat_size)
obj_db = ObjectFeatureDB(args.obj_ft_file, args.obj_feat_size)
dataset_class = SoonObjectNavBatch
if (args.aug is not None):
aug_instr_data = construct_i... |
('cms.components.page.signals.revalidate_vercel_frontend_task')
def test_revalidate_vercel_frontend(mock_task):
site = SiteFactory()
page = PageFactory()
site.root_page = page
site.save()
VercelFrontendSettingsFactory(revalidate_url=' revalidate_secret='test', site=site)
revalidate_vercel_fronte... |
def _add_validation_args(parser):
group = parser.add_argument_group(title='validation')
group.add_argument('--eval-iters', type=int, default=10, help='Number of iterations to run for evaluationvalidation/test for.')
group.add_argument('--eval-interval', type=int, default=1000, help='Interval between running... |
def _test_sharding_ec(tables: List[EmbeddingConfig], initial_state_dict: Dict[(str, Any)], rank: int, world_size: int, kjt_input_per_rank: List[KeyedJaggedTensor], sharder: ModuleSharder[nn.Module], backend: str, constraints: Optional[Dict[(str, ParameterConstraints)]]=None, local_size: Optional[int]=None) -> None:
... |
class MacroCommand(Command):
commands: List[Command]
def __init__(self, commands: List[Command]):
self.commands = commands
def execute(self) -> None:
for i in range(len(self.commands)):
self.commands[i].execute()
def undo(self) -> None:
for i in range(len(self.command... |
def print_module_summary(module, inputs, max_nesting=3, skip_redundant=True):
assert isinstance(module, torch.nn.Module)
assert (not isinstance(module, torch.jit.ScriptModule))
assert isinstance(inputs, (tuple, list))
entries = []
nesting = [0]
def pre_hook(_mod, _inputs):
nesting[0] += ... |
class CSVOutput(object):
def __init__(self, config: Config, fieldnames: List, abs_filename: str, overwrite_file: bool=True, delimiter: str=';'):
self.config = config
mode = ('w' if overwrite_file else 'a')
self.file_handler = open(os.path.join((abs_filename + '.csv')), mode)
self.csv... |
def ss_windowname(screenshot_manager):
screenshot_manager.test_window('One')
screenshot_manager.take_screenshot()
screenshot_manager.c.window.toggle_maximize()
screenshot_manager.take_screenshot()
screenshot_manager.c.window.toggle_minimize()
screenshot_manager.take_screenshot()
screenshot_m... |
class TestDirectoryRecursion():
.requires_unix
def test_infinite_loop_prevention(self, temp_dir):
project_dir = (temp_dir / 'project')
project_dir.ensure_dir_exists()
with project_dir.as_cwd():
config = {'tool': {'hatch': {'build': {'include': ['foo', 'README.md']}}}}
... |
.parametrize(('expr', 'expected_passed'), [('None', ['test_func[None]']), ('[1.3]', ['test_func[1.3]']), ('2-3', ['test_func[2-3]'])])
def test_keyword_option_parametrize(expr: str, expected_passed: List[str], pytester: Pytester) -> None:
pytester.makepyfile('\n import pytest\n .parametrize("arg", [No... |
class DocstringParamHintingTest(AbstractHintingTest):
def test_hint_param(self):
code = dedent(' class Sample(object):\n def a_method(self, a_arg):\n """:type a_arg: threading.Thread"""\n a_arg.is_a')
result = self._assist(code)
... |
class Time2ShieldRegenGetter(SmoothPointGetter):
def _getCommonData(self, miscParams, src, tgt):
return {'maxShieldAmount': src.item.ship.getModifiedItemAttr('shieldCapacity'), 'shieldRegenTime': (src.item.ship.getModifiedItemAttr('shieldRechargeRate') / 1000)}
def _calculatePoint(self, x, miscParams, s... |
def get_deps(factory_class: FactoryType, parent_factory_class: (FactoryType | None)=None, model_name: (str | None)=None) -> list[str]:
model_name = (get_model_name(factory_class) if (model_name is None) else model_name)
parent_model_name = (get_model_name(parent_factory_class) if (parent_factory_class is not No... |
def _optimizer(args: SharedArgs, steps_per_epoch: int) -> Optimizer:
learning_rate = _create_learning_rate(args, steps_per_epoch)
if args.decoupled_weight_decay:
weight_decay = _create_weight_decay(args, steps_per_epoch)
if (args.optimizer == OPTIMIZER_ADAM):
optimizer = tfa.optimize... |
class Honest(Policy):
def __init__(self, observation_space, action_space, config):
Policy.__init__(self, observation_space, action_space, config)
self.blocks = config['blocks']
self.fiftyone = config['fiftyone']
self.extended = config['extended']
def compute_actions(self, obs_bat... |
class IhexParser():
def __init__(self, path):
self.mem = []
self.segments = []
self.base = 0
with open(path, 'r') as f:
for line in f.read().splitlines():
self.parse_line(line.strip())
(begin, stream) = (0, b'')
for (addr, data) in ... |
class FastCronTab(CronTab):
def __init__(self, *args, **kwargs):
super(FastCronTab, self).__init__(*args, **kwargs)
self.every_minute = (args[0] == '* * * * *')
self.cached_now = None
self.cached_next = None
def next(self, now=None, *args, **kwargs):
if (now is None):
... |
class ChangeStream(Scaffold):
async def change_stream(self, chat_id: Union[(int, str)], stream: Optional[Stream]=None):
if (self._app is None):
raise NoMTProtoClientSet()
if (not self._is_running):
raise ClientNotStarted()
chat_id = (await self._resolve_chat_id(chat_i... |
def test_local_filename_dictionary_installed(tmpdir, monkeypatch):
monkeypatch.setattr(spell, 'dictionary_dir', (lambda : str(tmpdir)))
for lang_file in ['en-US-11-0.bdic', 'en-US-7-1.bdic', 'pl-PL-3-0.bdic']:
(tmpdir / lang_file).ensure()
assert (spell.local_filename('en-US') == 'en-US-11-0.bdic')
... |
def _pil_loader(path, cropArea=None, resizeDim=None, frameFlip=None):
with open(path, 'rb') as f:
img = Image.open(f)
resized_img = (img.resize(resizeDim, Image.ANTIALIAS) if (resizeDim != None) else img)
cropped_img = (resized_img.crop(cropArea) if (cropArea != None) else resized_img)
... |
def seek_sequential(hashes, outdir):
len_hashes = len(hashes)
pbar = tf.contrib.keras.utils.Progbar(len_hashes)
cprogress = tf.constant(0)
dataset_i = tf.data.Dataset.range(len_hashes)
iterator_i = dataset_i.make_one_shot_iterator()
next_element_i = iterator_i.get_next()
hash_i = tf.placehol... |
class WorkTask(Task):
def __init__(self, i, p, w, s, r):
super().__init__(i, p, w, s, r)
def fn(self, pkt, r):
w = r
assert isinstance(w, WorkerTaskRec)
super().fn(pkt, r)
if (pkt is None):
return self.waitTask()
if (w.destination == I_HANDLERA):
... |
class TestAutouseManagement():
def test_autouse_conftest_mid_directory(self, pytester: Pytester) -> None:
pkgdir = pytester.mkpydir('xyz123')
pkgdir.joinpath('conftest.py').write_text(textwrap.dedent(' import pytest\n (autouse=True)\n def app():\n ... |
def downsample_block(input, num_channel, kernel_size):
net = tf.contrib.layers.layer_norm(input, scale=True)
net = tf.nn.relu(net)
residual = slim.conv2d(activation_fn=None, inputs=net, num_outputs=num_channel, biases_initializer=None, kernel_size=[1, kernel_size], stride=[1, 2], padding='SAME')
residua... |
def catchSignals():
global catchingSigs
if catchingSigs:
return
catchingSigs = True
import signal
def f(sigNo, *args):
global inSigHandler
if inSigHandler:
return
inSigHandler = True
os.killpg(os.getpgrp(), sigNo)
sys.stderr.write(('\nCaugh... |
def test_new_end_state():
balance1 = 101
node_address = make_address()
end_state = NettingChannelEndState(node_address, balance1)
lock_secret = keccak(b'test_end_state')
lock_secrethash = sha256(lock_secret).digest()
assert (channel.is_lock_pending(end_state, lock_secrethash) is False)
asser... |
def normalize_index_name(index_name, legacy_index_map):
if (len(index_name) <= MAXIMUM_INDEX_NAME_LENGTH):
return index_name
if (index_name in legacy_index_map):
return legacy_index_map[index_name]
hashed = hashlib.sha256(index_name).hexdigest()
updated = ('%s_%s' % (index_name[0:MAXIMUM... |
_config
def test_floating_focus(manager):
manager.c.next_layout()
assert (len(manager.c.layout.info()['stacks']) == 2)
manager.test_window('two')
manager.test_window('one')
assert (manager.c.window.info()['width'] == 398)
assert (manager.c.window.info()['height'] == 578)
manager.c.window.tog... |
def test_direct_junction_offsets_pre_suc_2_right(direct_junction_right_lane_fixture):
(main_road, small_road, junction_creator) = direct_junction_right_lane_fixture
main_road.add_predecessor(xodr.ElementType.junction, junction_creator.id)
small_road.add_successor(xodr.ElementType.junction, junction_creator.... |
def _resolve_from_appdata(criteria_, app, timeout=None, retry_interval=None):
if (timeout is None):
timeout = Timings.window_find_timeout
if (retry_interval is None):
retry_interval = Timings.window_find_retry
global cur_item
matched_control = app.GetMatchHistoryItem(cur_item)
cur_it... |
def test_no_ordering_with_shorter_marker_prefix(marker_test):
result = marker_test.runpytest('-v', '--order-marker-prefix=m')
result.assert_outcomes(passed=3, skipped=0)
result.stdout.fnmatch_lines(['test_marker.py::test_a PASSED', 'test_marker.py::test_b PASSED', 'test_marker.py::test_c PASSED']) |
class Optim(object):
def set_parameters(self, params):
params_ = params
self.params = list(params_)
if (self.method == 'sgd'):
if (not self.zeror):
self.optimizer = optim.SGD(self.params, lr=self.lr, weight_decay=self.weight_decay, momentum=0.0)
else:
... |
()
def repositories_hg_git(tmp_path: Path) -> tuple[(WorkDir, WorkDir)]:
tmp_path = tmp_path.resolve()
path_git = (tmp_path / 'repo_git')
path_git.mkdir()
wd = WorkDir(path_git)
wd('git init')
wd('git config user.email ')
wd('git config user.name "a test"')
wd.add_command = 'git add .'
... |
class QNTPServer():
def __init__(self, **kwargs):
self.auto_disabled = None
self.process = None
self.uuid = (((('honeypotslogger' + '_') + __class__.__name__) + '_') + str(uuid4())[:8])
self.config = kwargs.get('config', '')
if self.config:
self.logs = setup_logge... |
class Effect4812(BaseEffect):
type = 'passive'
def handler(fit, module, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'ECM')), 'scanRadarStrengthBonus', module.getModifiedItemAttr('ecmStrengthBonusPercent'), stackingPenalties=True, **kwargs) |
def test_expand_line():
redirected = '/redirected'
link = '/resource'
with start_server(Response(link, 301, {'Location': redirected}), Response(redirected, 200, {})) as url:
fmt = 'before %s after'
line = (fmt % url(link))
expected = (fmt % url(redirected))
assert (expected =... |
def _find_all_unkown_paths_per_recursive_node(node: _RecursivePathNode, include_directories: bool) -> Generator[(Path, None, None)]:
if (node.is_unknown and (node.is_file or (node.is_dir and include_directories))):
(yield node.path)
else:
for n in node.sub_nodes:
(yield from _find_al... |
class SAC(object):
def __init__(self, state_dim, action_dim, max_action, batch_size=256, discount=0.99, tau=0.005, policy_noise=0.2, noise_clip=0.5, policy_freq=1, actor_lr=0.0003, critic_lr=0.0003, temp_lr=0.0003, alpha=0.2, target_entropy=None, device=torch.device('cuda')):
self.device = device
se... |
class _PickleCore(_BaseCore):
class CacheChangeHandler(PatternMatchingEventHandler):
def __init__(self, filename, core, key):
PatternMatchingEventHandler.__init__(self, patterns=[('*' + filename)], ignore_patterns=None, ignore_directories=True, case_sensitive=False)
self.core = core
... |
class CharVocab():
def from_data(cls, data, *args, **kwargs):
chars = set()
for string in data:
chars.update(string)
return cls(chars, *args, **kwargs)
def __init__(self, chars, ss=SS):
if ((ss.bos in chars) or (ss.eos in chars) or (ss.pad in chars) or (ss.unk in char... |
def sz_operator(n_spatial_orbitals: int) -> FermionOperator:
if (not isinstance(n_spatial_orbitals, int)):
raise TypeError('n_orbitals must be specified as an integer')
operator = FermionOperator()
n_spinless_orbitals = (2 * n_spatial_orbitals)
for ni in range(n_spatial_orbitals):
operat... |
class FileType(DictMixin):
__module__ = 'mutagen'
info = None
tags = None
filename = None
_mimes = ['application/octet-stream']
def __init__(self, *args, **kwargs):
if ((not args) and (not kwargs)):
warnings.warn('FileType constructor requires a filename', DeprecationWarning)... |
class TopologicalCircuit():
def __init__(self, treg: TopologicalRegister):
self.treg = treg
self.qreg: Dict[(str, QuantumRegister)] = {}
self.creg: Dict[(str, ClassicalRegister)] = {}
self.circ = treg.circ
def add_creg(self, size=None, name=None, bits=None, override: bool=False) ... |
def find_version(*file_paths):
try:
with io.open(os.path.join(PROJECTDIR, *file_paths), encoding='utf8') as fp:
version_file = fp.read()
pattern = '^__version__ = version = [\'\\"]([^\'\\"]*)[\'\\"]'
version_match = re.search(pattern, version_file, re.M)
return versio... |
def test_greater_than():
bb = BloqBuilder()
bitsize = 5
q0 = bb.add_register('a', bitsize)
q1 = bb.add_register('b', bitsize)
anc = bb.add_register('result', 1)
(q0, q1, anc) = bb.add(GreaterThan(bitsize, bitsize), a=q0, b=q1, target=anc)
cbloq = bb.finalize(a=q0, b=q1, result=anc)
cbloq... |
.parametrize('file_name, elem_id, source, input_text', [('textarea.html', 'qute-textarea', 'clipboard', 'qutebrowser'), ('textarea.html', 'qute-textarea', 'keypress', 'superqutebrowser'), ('input.html', 'qute-input', 'clipboard', 'amazingqutebrowser'), ('input.html', 'qute-input', 'keypress', 'awesomequtebrowser'), pyt... |
(frozen=True, eq=False)
class SubscribingAtomicList(AtomicList):
subscriptions: defaultdict[(Event, list[int])] = dataclasses.field(default_factory=(lambda : defaultdict(list)))
def subscribe(self, filter_: UniqueFilter, *events: Event) -> None:
for event in events:
if (filter_ not in self.s... |
def first_run(save_path):
txt_file = os.path.join(save_path, 'first_run.txt')
if (not os.path.exists(txt_file)):
open(txt_file, 'w').close()
else:
saved_epoch = open(txt_file).read()
if (saved_epoch is None):
print('You forgot to delete [first run file]')
retu... |
class F12_Partition(F11_Partition):
removedKeywords = F11_Partition.removedKeywords
removedAttrs = F11_Partition.removedAttrs
def _getParser(self):
op = F11_Partition._getParser(self)
op.add_argument('--escrowcert', metavar='<url>', version=F12, help='\n Load an X.509 ... |
class Job(CPIBase, Async):
def __init__(self, api, adaptor):
_cpi_base = super(Job, self)
_cpi_base.__init__(api, adaptor)
def init_instance(self, info, ttype):
pass
def init_instance_async(self, info, ttype):
pass
def get_id(self, ttype):
pass
def get_id_asyn... |
class PoolFormerPreTrainedModel(PreTrainedModel):
config_class = PoolFormerConfig
base_model_prefix = 'poolformer'
main_input_name = 'pixel_values'
supports_gradient_checkpointing = True
def _init_weights(self, module):
if isinstance(module, (nn.Linear, nn.Conv2d)):
module.weight... |
def main():
parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
(model_args, data_args, training_args) = parser.parse_args_into_dataclasses()
print('Setup Data')
if ('VQA_RAD' in data_args.Train_csv_path):
training_args.run_name = (training_args.run_name + ... |
def generateVideo(df, df_complete, numFrame):
hitpointFrame = df[(df.hitpoint == 1)].reset_index(drop=True)['Frame']
actual = [0 for _ in range(len(df_complete))]
marked = [0 for _ in range(len(df_complete))]
coverage = 5
for x in hitpointFrame:
actual[(x - 1)] = 1
if ((x > coverage)... |
.parametrize('device', get_available_devices())
def test_memmap_same_device_as_tensor(device):
t = torch.tensor([1], device=device)
m = MemmapTensor.from_tensor(t)
assert (t.device == torch.device(device))
assert (m.device == torch.device(device))
for other_device in get_available_devices():
... |
class uvm_reg_field(uvm_object):
def __init__(self, name='uvm_reg_field'):
super().__init__(name)
self._parent = None
self._size = None
self._lsb_pos = None
self._access = None
self._is_volatile = None
self._reset = None
def configure(self, parent, size, l... |
def prune_small_rho_grids_(ks, cell, dm, grids, kpts):
rho = ks.get_rho(dm, grids, kpts)
n = numpy.dot(rho, grids.weights)
if (abs((n - cell.nelectron)) < (NELEC_ERROR_TOL * n)):
rho *= grids.weights
idx = (abs(rho) > (ks.small_rho_cutoff / grids.weights.size))
logger.debug(ks, 'Drop... |
class DrawBoxTensor(object):
def __init__(self, cfgs):
self.cfgs = cfgs
self.drawer = DrawBox(cfgs)
def only_draw_boxes(self, img_batch, boxes, method, head=None, is_csl=False):
boxes = tf.stop_gradient(boxes)
img_tensor = tf.squeeze(img_batch, 0)
img_tensor = tf.cast(img... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.