code stringlengths 281 23.7M |
|---|
def get_cached_module_file(pretrained_model_name_or_path: Union[(str, os.PathLike)], module_file: str, cache_dir: Optional[Union[(str, os.PathLike)]]=None, force_download: bool=False, resume_download: bool=False, proxies: Optional[Dict[(str, str)]]=None, use_auth_token: Optional[Union[(bool, str)]]=None, revision: Opti... |
def main(argv):
args = parse_args(argv)
args.ws_dir = args.ws_dir.absolute()
if (args.prefix is not None):
args.prefix = args.prefix.absolute()
(freetds_archive, iconv_archive) = download(args)
if (platform.system() == 'Windows'):
os.environ['PATH'] += f';{args.msys}'
build_w... |
def resnet_arg_scope(weight_decay=0.0001, batch_norm_decay=0.997, batch_norm_epsilon=1e-05, batch_norm_scale=True, activation_fn=tf.nn.relu, use_batch_norm=True, batch_norm_updates_collections=tf.GraphKeys.UPDATE_OPS):
batch_norm_params = {'decay': batch_norm_decay, 'epsilon': batch_norm_epsilon, 'scale': batch_nor... |
def load_custom_pretrained(model: nn.Module, pretrained_cfg: Optional[Dict]=None, load_fn: Optional[Callable]=None):
pretrained_cfg = (pretrained_cfg or getattr(model, 'pretrained_cfg', None))
if (not pretrained_cfg):
_logger.warning('Invalid pretrained config, cannot load weights.')
return
... |
def read_platform_numbers(filename, in_upper=False, num_as_int=False):
out_dict = {}
with open(filename, 'r') as fid:
for row in fid:
if (not row.startswith('#')):
parts = row.split()
if (len(parts) < 2):
continue
platform =... |
def generate_random_log_paths(sample_len: int, sample_size: int, mean: float, std: float, leverage: float=1.0):
mean = (mean * leverage)
std = (std * leverage)
mean = (mean - ((0.5 * std) * std))
time = np.arange(1, (1 + sample_len))
returns_vector = np.random.normal(loc=mean, scale=std, size=((samp... |
def str_dec(string):
res = ''
prev_slash = False
for ch in string:
if (ch == chr(92)):
if (not prev_slash):
prev_slash = True
else:
res += ch
prev_slash = False
else:
prev_slash = False
res += ch
... |
def _identify_radius(r):
r = r.replace(' ', '')
try:
if (r.startswith('(') and r.endswith(')')):
(rx, ry) = map(float, r.lstrip('(').rstrip(')').split(','))
elif (r == 'None'):
r = None
else:
r = float(r)
rx = ry = r
return (rx, ry)... |
def path_logger(result_dir, log_time):
streamHandler = logging.StreamHandler()
streamHandler.setLevel(logging.DEBUG)
global logger
logger = logging.getLogger('basic')
logger.setLevel(logging.DEBUG)
path_logging = os.path.join(result_dir, f'{log_time}')
fileHandler = logging.FileHandler(path_... |
class M(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x, w1, w2):
val1 = torch.neg(w1)
m1 = torch.cat([val1, w2]).sum()
val2 = torch.neg(w1)
m2 = torch.cat([val2, w2]).sum()
return ((x + torch.max(m1)) + torch.max(m2)) |
class M2M100Tokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
model_input_names = ['input_ids', 'attention_mask']
prefix_tokens: List[int] = []
suffix_tokens... |
def send_new_schedule_invitation_answer(schedule_item, request):
invitation_admin_url = request.build_absolute_uri(schedule_item.get_invitation_admin_url())
schedule_item_admin_url = request.build_absolute_uri(schedule_item.get_admin_url())
submission = schedule_item.submission
publish_message('NewSched... |
class TestLeadAcidLOQS(TestCase):
def test_well_posed(self):
options = {'thermal': 'isothermal'}
model = pybamm.lead_acid.LOQS(options)
model.check_well_posedness()
model = pybamm.lead_acid.LOQS(build=False)
model.build_model()
model.check_well_posedness()
def tes... |
class DataTrainingArguments():
dataset_name: Optional[str] = field(default='cifar10', metadata={'help': 'Name of a dataset from the datasets package'})
dataset_config_name: Optional[str] = field(default=None, metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'})
imag... |
def cast_tensor_type(inputs, src_type, dst_type):
if isinstance(inputs, torch.Tensor):
return inputs.to(dst_type)
elif isinstance(inputs, str):
return inputs
elif isinstance(inputs, np.ndarray):
return inputs
elif isinstance(inputs, abc.Mapping):
return type(inputs)({k: c... |
class Simulator(multiprocessing.Process):
class State():
PRE_START = 0
CALLING = 1
PLAYING = 2
END = 3
templates = load_templates()
mini_templates = load_mini_templates(templates)
def __init__(self, idx, hwnd, pipe_sim2exps, pipe_exps2sim, pipe_sim2coord, pipe_coord2sim, ... |
class ModelSaverBase(object):
def __init__(self, base_path, model, model_opt, fields, optim, keep_checkpoint=(- 1)):
self.base_path = base_path
self.model = model
self.model_opt = model_opt
self.fields = fields
self.optim = optim
self.last_saved_step = None
se... |
class Assigning():
def __init__(self, value: int, name: str) -> None:
self.value = value
self.name = name
def new_attr(self, newvalue: int, newname: str) -> None:
self = newvalue
self.name = newname
def new_cls(cls, newtype: type) -> type:
cls = newtype
return... |
def all_values_full(args: list[Register], blocks: list[BasicBlock]) -> list[Value]:
values: list[Value] = list(args)
seen_registers = set(args)
for block in blocks:
for op in block.ops:
for source in op.sources():
if (isinstance(source, Register) and (source not in seen_r... |
def test_validate_helm_oci_manifest():
manifest_bytes = '{\n "schemaVersion":2,\n "config":{\n "mediaType":"application/vnd.cncf.helm.config.v1+json",\n "digest":"sha256:65a07b841ece031e6d0ec5eb948eacb17aa6d7294cdeb01d5348e",\n "size":141\n },\n "layers": [\n {\n "... |
def send_nsca(code, message, nscahost, hostname=None, service=None, nscabin='send_nsca', nscaconf=None):
if (not hostname):
hostname = platform.node()
command = [nscabin, '-H', nscahost]
if nscaconf:
command += ['-c', nscaconf]
code = str(code)
if service:
input_string = ('\t... |
def densenet121(num_classes, loss, pretrained='imagenet', **kwargs):
model = DenseNet(num_classes=num_classes, loss=loss, num_init_features=64, growth_rate=32, block_config=(6, 12, 24, 16), fc_dims=None, dropout_p=None, **kwargs)
if (pretrained == 'imagenet'):
init_pretrained_weights(model, model_urls['... |
_config
def test_bsp_window_focus_cycle(manager):
manager.test_window('one')
manager.test_window('two')
manager.test_window('float1')
manager.c.window.toggle_floating()
manager.test_window('float2')
manager.c.window.toggle_floating()
manager.test_window('three')
assert (manager.c.layout.... |
class XMLHelperTestCases(unittest.TestCase):
def tearDown(self):
os.unlink('__unittests.xml')
def assertReadWriteSame(self, props):
WriteDialogToFile('__unittests.xml', props)
read_props = ReadPropertiesFromFile('__unittests.xml')
self.assertEqual(props, read_props)
def testO... |
def _start_kernel():
if (sys._ipython_app and sys._ipython_kernel_running):
return sys._ipython_app
import IPython
from ipykernel.kernelapp import IPKernelApp
from zmq.eventloop import ioloop
def _IPKernelApp_start(self):
if (self.poller is not None):
self.poller.start()
... |
class Resolver():
def __init__(self, callback, resolve_on_error, time_to_live=(60 * 30)):
self.callback = callback
self.resolve_on_error = resolve_on_error
self._cache = {}
self._time_to_live = time_to_live
self._cache_ttl = defaultdict(set)
self._clear_every = 2
... |
def test_max_iterations():
this_dir = os.path.dirname(os.path.realpath(__file__))
file = os.path.join(this_dir, 'temp_test_max_iterations_file.txt')
mem = memory_usage((write_line, (file,), dict()), max_usage=True, max_iterations=1)
n_lines = sum((1 for line in open(file)))
os.remove(file)
asser... |
class TestArgComplete():
.skipif("sys.platform in ('win32', 'darwin')")
def test_compare_with_compgen(self, tmp_path: Path, monkeypatch: MonkeyPatch) -> None:
from _pytest._argcomplete import FastFilesCompleter
ffc = FastFilesCompleter()
fc = FilesCompleter()
monkeypatch.chdir(tm... |
def set_rp_acl(rp, entry_list=None, default_entry_list=None, map_names=1):
assert (rp.conn is Globals.local_connection), 'Set ACLs of path should only be done locally not over {conn}.'.format(conn=rp.conn)
if entry_list:
acl = _list_to_acl(entry_list, map_names)
else:
acl = posix1e.ACL()
... |
def save_model(model: nn.Module, iteration: int, suffix: str) -> None:
os.makedirs(args.save_folder, exist_ok=True)
save_path = os.path.join(args.save_folder, '{}_{}_{}_kd{}_size{}_anchor{}_{}_{}.pth'.format(args.dataset, args.neck, args.backbone, args.kd, args.image_size, args.anchor_size, ('MG' if args.mutual... |
class GaussianMLPRegressor(LayersPowered, Serializable):
def __init__(self, name, input_shape, output_dim, mean_network=None, hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.tanh, optimizer=None, use_trust_region=True, step_size=0.01, learn_std=True, init_std=1.0, adaptive_std=False, std_share_network=False, std_h... |
class CustomMapping(object):
def __init__(self, *args, **kwargs):
self._d = dict(*args, **kwargs)
def __getitem__(self, key):
return self._d[key]
def __setitem__(self, key, val):
self._d[key] = val
def __delitem__(self, key):
del self._d[key]
def __iter__(self):
... |
def train(train_data, test_data, user_size, item_size):
with tf.Session() as sess:
iterator = tf.data.Iterator.from_structure(train_data.output_types, train_data.output_shapes)
model = NCF.NCF(FLAGS.embedding_size, user_size, item_size, FLAGS.lr, FLAGS.optim, FLAGS.initializer, FLAGS.loss_func, FLAG... |
class ZeroDimensionalSpatialMethod(pybamm.SpatialMethod):
def __init__(self, options=None):
super().__init__(options)
def build(self, mesh):
self._mesh = mesh
def boundary_value_or_flux(self, symbol, discretised_child, bcs=None):
return discretised_child
def mass_matrix(self, sym... |
def transform(obj: object, cls: Type[T], *, mapper: Callable[([Dict[(str, Any)]], Dict[(str, Any)])]=None, dump_cls: type=None, dump_args: List[Any]=None, dump_kwargs: List[Dict[(str, Any)]]=None, **kwargs) -> T:
dump_args_ = (dump_args or [])
dump_kwargs_ = (dump_kwargs or {})
dumped = dump(obj, dump_cls, ... |
class UniF_AGRU(nn.Module):
def __init__(self, emodict, worddict, embedding, args):
super(UniF_AGRU, self).__init__()
self.num_classes = emodict.n_words
self.embeddings = embedding
self.gpu = args.gpu
self.hops = args.hops
self.wind_1 = args.wind1
self.utt_gru... |
(derivate=True, coderize=True)
_loss
def gaussian_focal_loss(pred, gaussian_target, alpha=2.0, gamma=4.0):
eps = 1e-12
pos_weights = gaussian_target.eq(1)
neg_weights = (1 - gaussian_target).pow(gamma)
pos_loss = (((- (pred + eps).log()) * (1 - pred).pow(alpha)) * pos_weights)
neg_loss = (((- ((1 - ... |
class TestParametersCLI(TestCase):
def test_error(self):
with self.assertRaisesRegex(NotImplementedError, 'deprecated'):
pybamm.add_parameter()
with self.assertRaisesRegex(NotImplementedError, 'deprecated'):
pybamm.edit_parameter()
with self.assertRaisesRegex(NotImple... |
class DirListAction(Action, ProcessableAction):
mandatoryparams = ['directory']
optionalparams = ['dirmask']
varexpansion = ['directory', 'filename']
def __init__(self, execparams, parent):
Action.__init__(self, execparams=execparams, parent=parent)
def Execute(self):
Action.Execute(... |
class Effect5243(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredChargeBoost((lambda mod: (mod.charge.requiresSkill('Rockets') or mod.charge.requiresSkill('Light Missiles'))), 'emDamage', ship.getModifiedItemAttr('shipBonusCF2'), skill='Calda... |
def prepare_z_y(G_batch_size, dim_z, nclasses, device='cuda', fp16=False, z_var=1.0, N_target_cate=100):
z_ = Distribution(torch.randn(G_batch_size, dim_z, requires_grad=False))
z_.init_distribution('normal', mean=0, var=z_var)
z_ = z_.to(device, (torch.float16 if fp16 else torch.float32))
if fp16:
... |
def compute_cov_g(g, classname, layer_info, fast_cnn):
batch_size = g.size(0)
if (classname == 'Conv2d'):
if fast_cnn:
g = g.view(g.size(0), g.size(1), (- 1))
g = g.sum((- 1))
else:
g = g.transpose(1, 2).transpose(2, 3).contiguous()
g = g.view((- 1... |
def run(model_args, data_args, training_args, additional_training_args):
setup_logging(training_args)
set_seed(training_args.seed)
datasets = load_dataset(data_args.dataset_name, data_args.dataset_config_name)
text_column_name = 'text'
label_column_name = 'label'
label_list = datasets['train'].f... |
def get_resnet_v1_s(input_x, scope='resnet50_v1s', bottleneck_nums=[3, 4, 6, 3], base_channels=[64, 128, 256, 512], freeze=[True, False, False, False, False], is_training=True, freeze_norm=False, num_cls=1000, dropout=False):
(net, fet_dict) = get_resnet_v1_s_base(input_x=input_x, scope=scope, bottleneck_nums=bottl... |
class TestBackBone(unittest.TestCase):
def test_resnet_scriptability(self):
cfg = get_cfg()
resnet = build_resnet_backbone(cfg, ShapeSpec(channels=3))
scripted_resnet = torch.jit.script(resnet)
inp = torch.rand(2, 3, 100, 100)
out1 = resnet(inp)['res4']
out2 = scripte... |
class ExpReplay(DataFlow, Callback):
def __init__(self, predictor_io_names, player, state_shape, num_actions, batch_size, memory_size, init_memory_size, init_exploration, update_frequency, encoding_file='../AutoEncoder/encoding.npy'):
init_memory_size = int(init_memory_size)
for (k, v) in locals().i... |
class TestRaises(TestCase):
def test_simple(self):
self.assertRaisesRegex(RunTimeError, 'text .* match', someFunc)
def test_simple_with_newlines(self):
self.assertRaisesRegex(RunTimeError, 'text .* match', someFunc)
def test_args(self):
self.assertRaisesRegex(RunTimeError, 'text .* m... |
class Migration(migrations.Migration):
dependencies = [('options', '0033_option_help')]
operations = [migrations.AddField(model_name='option', name='view_text_lang1', field=models.TextField(blank=True, help_text='The view text for this option in the primary language.', null=True, verbose_name='View text (primar... |
def read_files(doc_file, keys_file):
doc_dict = OrderedDict()
keys_dict = OrderedDict()
with open(doc_file) as f_doc:
for line in f_doc:
line_json = json.loads(line)
doc_dict[line_json['docid']] = line_json['text']
with open(keys_file) as f_keys:
contents = f_keys... |
class PackedData():
class _NoData():
pass
NO_DATA = _NoData()
def __init__(self, node, data):
self.left = self.NO_DATA
self.right = self.NO_DATA
if data:
if (node.left is not None):
self.left = data[0]
if (len(data) > 1):
... |
def setup_environment():
global _ENV_SETUP_DONE
if _ENV_SETUP_DONE:
return
_ENV_SETUP_DONE = True
_configure_libraries()
custom_module_path = os.environ.get('DETECTRON2_ENV_MODULE')
if custom_module_path:
setup_custom_environment(custom_module_path)
else:
pass |
class TestCase():
def __init__(self, test_name: str, model, input_shape, valid_hx=False, sequence_lens=None, device='cpu'):
self.test_name = test_name
self.model = model.to(device)
self.input_shape = input_shape
self.valid_hx = valid_hx
self.device = device
self.seque... |
def _test():
import torch
pretrained = False
models = [pyramidnet101_a360]
for model in models:
net = model(pretrained=pretrained)
net.eval()
weight_count = _calc_width(net)
print('m={}, {}'.format(model.__name__, weight_count))
assert ((model != pyramidnet101_a36... |
def test_ki_with_broken_threads() -> None:
thread = threading.main_thread()
original = threading._active[thread.ident]
try:
del threading._active[thread.ident]
_core.enable_ki_protection
async def inner() -> None:
assert (signal.getsignal(signal.SIGINT) != signal.default_... |
def test_setup_cfg_no_version(tmp_path):
setup_cfg = (tmp_path / 'setup.cfg')
setup_cfg.write_text(dedent('\n [tool:isort]\n profile = black\n '))
decl = PatternVersionDeclaration(setup_cfg.resolve(), '^version = (?P<version>.*)$')
assert (decl.parse() == set()) |
.skipif((not is_py39_plus), reason='literals and annotated are 3.9+')
def test_type_names_with_quotes():
from typing import Annotated, Literal, Union
converter = Converter()
assert (converter.structure({1: 1}, Dict[(Annotated[(int, "'")], int)]) == {1: 1})
converter.register_structure_hook_func((lambda ... |
class FactorVaeTest(absltest.TestCase):
def test_metric(self):
ground_truth_data = dummy_data.IdentityObservationsData()
representation_function = (lambda x: x)
random_state = np.random.RandomState(0)
scores = factor_vae.compute_factor_vae(ground_truth_data, representation_function, ... |
def aug_args_with_log(args):
id_process = os.getpid()
time_current = datetime.datetime.now().isoformat()
args.Version = torch.__version__
args.ID = id_process
args.TIME = time_current
path_storage = os.path.abspath(args.PathStorage)
args.PathDomain = os.path.join(path_storage, 'domains', arg... |
class TracesFileCache(object):
caches = {}
def __init__(self, cachedir):
self.cachedir = cachedir
self.dircaches = {}
self.modified = set()
util.ensuredir(self.cachedir)
def get(self, abspath):
dircache = self._get_dircache_for(abspath)
if (abspath in dircache... |
def virtual_scane_one_model(model_dir, worker_id):
print(('Scanning ' + model_dir))
tmp_model_name = (('tmp' + str(worker_id)) + '.ply')
TMP_DATA_PATH = ('./tmp' + str(worker_id))
TMP_PLY_POINTCLOUD_PATH = (('./tmp' + str(worker_id)) + '.ply_output')
if (not os.path.exists(TMP_DATA_PATH)):
o... |
class DPM_Solver():
def __init__(self, model_fn, noise_schedule, predict_x0=False, thresholding=False, max_val=1.0):
self.model = model_fn
self.noise_schedule = noise_schedule
self.predict_x0 = predict_x0
self.thresholding = thresholding
self.max_val = max_val
def noise_p... |
def load_data(args):
(train, validate, test) = process_data.get_data(args.text_only)
word_vector_path = '../Data/weibo/word_embedding.pickle'
f = open(word_vector_path, 'rb')
weight = pickle.load(f)
(W, W2, word_idx_map, vocab, max_len) = (weight[0], weight[1], weight[2], weight[3], weight[4])
a... |
def get_public_key(message: bytes, signature: Signature, hasher: Callable[([bytes], bytes)]=eth_sign_sha3) -> PublicKey:
hashed_message = hasher(message)
if (signature[(- 1)] >= 27):
signature = Signature((signature[:(- 1)] + bytes([(signature[(- 1)] - 27)])))
try:
sig = keys.Signature(signa... |
class FusedQdqLinear(torch.autograd.Function):
def forward(ctx, inp, weight, bias, weight_encoding_min, weight_encoding_max, weight_quantizer):
ctx.save_for_backward(inp, weight, bias, weight_encoding_min, weight_encoding_max)
ctx.weight_quantizer = weight_quantizer
(qdq_weight, _) = ste.cal... |
def _parse_speaker_info(data_root):
speaker_info_path = join(data_root, 'gender_f0range.txt')
if (not exists(speaker_info_path)):
raise RuntimeError("File {} doesn't exist".format(speaker_info_path))
speaker_info = OrderedDict()
terms = ['speaker', 'Male_or_Female', 'minf0[Hz]', 'maxf0[Hz]']
... |
class StandardTransform(object):
def __init__(self, transform=None, target_transform=None):
self.transform = transform
self.target_transform = target_transform
def __call__(self, input, target):
if (self.transform is not None):
input = self.transform(input)
if (self.t... |
def test_check_output_with_called_process_error(tmp_path: Path, tmp_venv: VirtualEnv, mocker: MockerFixture) -> None:
mocker.patch('subprocess.check_output', side_effect=subprocess.CalledProcessError(42, 'some_command', 'some output', 'some error'))
with pytest.raises(EnvCommandError) as error:
tmp_venv... |
class DataCollatorForMaskedLM(DataCollatorForLanguageModeling):
def torch_mask_tokens(self, inputs: Any, special_tokens_mask: Optional[Any]=None) -> Tuple[(Any, Any)]:
import torch
labels = inputs.clone()
probability_matrix = torch.full(labels.shape, self.mlm_probability)
if (special... |
class UnexpectedEOF(ParseError, UnexpectedInput):
expected: 'List[Token]'
def __init__(self, expected, state=None, terminals_by_name=None):
super(UnexpectedEOF, self).__init__()
self.expected = expected
self.state = state
from .lexer import Token
self.token = Token('<EOF>... |
def _conv2d_gradfix(transpose, weight_shape, stride, padding, output_padding, dilation, groups):
ndim = 2
weight_shape = tuple(weight_shape)
stride = _tuple_of_ints(stride, ndim)
padding = _tuple_of_ints(padding, ndim)
output_padding = _tuple_of_ints(output_padding, ndim)
dilation = _tuple_of_in... |
class AwaitExpr(Expression):
__slots__ = ('expr',)
__match_args__ = ('expr',)
expr: Expression
def __init__(self, expr: Expression) -> None:
super().__init__()
self.expr = expr
def accept(self, visitor: ExpressionVisitor[T]) -> T:
return visitor.visit_await_expr(self) |
(short_help='Run commands within project environments')
('args', required=True, nargs=(- 1))
('--env', '-e', 'env_names', multiple=True, help='The environments to target')
('--include', '-i', 'included_variable_specs', multiple=True, help='The matrix variables to include')
('--exclude', '-x', 'excluded_variable_specs',... |
def compute_output_dims_lengths(array_name: str, loop_orders, sub) -> str:
dims_c_code = ''
for (i, candidates) in enumerate(zip(*loop_orders)):
for (j, candidate) in enumerate(candidates):
if (candidate != 'x'):
var = sub[f'lv{int(j)}']
dims_c_code += f'''{ar... |
def rolling_volatility(returns, benchmark=None, period=126, period_label='6-Months', periods_per_year=252, lw=1.5, fontname='Arial', grayscale=False, figsize=(10, 3), ylabel='Volatility', subtitle=True, savefig=None, show=True):
returns = _stats.rolling_volatility(returns, period, periods_per_year)
if (benchmar... |
def get_num_synset_2012_images(path, synsets_2012, files_to_skip=None):
if path:
logging.info('Attempting to read number of leaf images from %s...', path)
if tf.io.gfile.exists(path):
with tf.io.gfile.GFile(path, 'r') as f:
num_synset_2012_images = json.load(f)
... |
class GradCAMElementWise(BaseCAM):
def __init__(self, model, target_layers, use_cuda=False, reshape_transform=None):
super(GradCAMElementWise, self).__init__(model, target_layers, use_cuda, reshape_transform)
def get_cam_image(self, input_tensor, target_layer, target_category, activations, grads, eigen_... |
def make_variable_state_initializer(**kwargs):
def variable_state_initializer(shape, batch_size, dtype, index):
args = kwargs.copy()
if args.get('name'):
args['name'] = ((args['name'] + '_') + str(index))
else:
args['name'] = ('init_state_' + str(index))
args[... |
class Stream(StreamWriter):
def __init__(self, reader: StreamReader, writer: StreamWriter) -> None:
super().__init__(writer._transport, writer._protocol, writer._reader, writer._loop)
self.remote = self.get_extra_info('peername')
def read(self, n: int=(- 1)) -> bytes:
return self._reader... |
.skipif((not hasattr(m, 'load_variant')), reason='no <variant>')
def test_variant(doc):
assert (m.load_variant(1) == 'int')
assert (m.load_variant('1') == 'std::string')
assert (m.load_variant(1.0) == 'double')
assert (m.load_variant(None) == 'std::nullptr_t')
assert (m.load_variant_2pass(1) == 'int... |
class ID3OptionParser(OptionParser):
def __init__(self):
mutagen_version = '.'.join(map(str, mutagen.version))
my_version = '.'.join(map(str, VERSION))
version = ('mid3iconv %s\nUses Mutagen %s' % (my_version, mutagen_version))
return OptionParser.__init__(self, version=version, usag... |
class XTSECalendarTestCase(ExchangeCalendarTestBase, TestCase):
answer_key_filename = 'xtse'
calendar_class = XTSEExchangeCalendar
MAX_SESSION_HOURS = 6.5
def test_2012(self):
expected_holidays_2012 = [pd.Timestamp('2012-01-02', tz=UTC), pd.Timestamp('2012-02-20', tz=UTC), pd.Timestamp('2012-04-... |
class CyberpunkAWS():
def __init__(self, expert_env, novice_env, horizon, itrs, trajs, imsize, expert_pkl, **kwargs):
self.expert_env = expert_env
self.novice_env = novice_env
self.horizon = horizon
self.itrs = itrs
self.trajs = trajs
self.expert_pkl = expert_pkl
... |
def test_unittest_not_shown_in_traceback(pytester: Pytester) -> None:
pytester.makepyfile('\n import unittest\n class t(unittest.TestCase):\n def test_hello(self):\n x = 3\n self.assertEqual(x, 4)\n ')
res = pytester.runpytest()
res.stdout.no_fnmatch... |
class Client(QDialog):
def __init__(self, parent=None):
super(Client, self).__init__(parent)
self.blockSize = 0
self.currentFortune = None
hostLabel = QLabel('&Server name:')
self.hostLineEdit = QLineEdit('fortune')
hostLabel.setBuddy(self.hostLineEdit)
self.s... |
def test_no_initial_bytes(rgb_data_and_profile):
(data, profile) = rgb_data_and_profile
with MemoryFile() as memfile:
with memfile.open(**profile) as dst:
dst.write(data)
view = memfile.getbuffer()
assert (view.size > 1000000)
data = bytes(bytearray(view))
with Me... |
class PageViewSet(ModelViewSet):
permission_classes = ((HasModelPermission | HasObjectPermission),)
serializer_class = PageSerializer
filter_backends = (SearchFilter, DjangoFilterBackend)
search_fields = ('uri', 'title')
filterset_fields = ('attribute', 'uri', 'uri_prefix', 'uri_path', 'comment', 'i... |
class FontConfigSearchPattern(FontConfigPattern):
def __init__(self, fontconfig):
super(FontConfigSearchPattern, self).__init__(fontconfig)
self.name = None
self.bold = False
self.italic = False
self.size = None
def match(self):
self._prepare_search_pattern()
... |
def test_retry_exec_iteration_handlederror_with_stopon():
rd = RetryDecorator({'max': 3, 'stopOn': '{k1}'})
context = Context({'k1': ['KeyError', 'ArbError']})
mock = MagicMock()
err = HandledError()
err.__cause__ = ValueError('arb')
mock.side_effect = err
with patch_logger('pypyr.dsl', logg... |
def test_transform_multiply(test, device, n):
a = wp.transform((0.0, 1.0, 0.0), wp.utils.quat_identity())
x = []
for i in range(10):
x.append(wp.utils.transform_identity())
xforms = wp.array(x, dtype=wp.transform, device=device)
wp.launch(transform_multiply, dim=n, inputs=[xforms, a], device... |
.parametrize('version,parts,expected', [('3.4.5', dict(major=2, minor=5), '2.5.5'), ('3.4.5', dict(major=2, minor=5, patch=10), '2.5.10'), ('3.4.5-alpha.1.2', dict(major=2), '2.4.5-alpha.1.2'), ('3.4.5-alpha.1.2', dict(build='x1'), '3.4.5-alpha.1.2+x1'), ('3.4.5+build1', dict(major=2), '2.4.5+build1')])
def test_should... |
class WildcardPattern(BasePattern):
def __init__(self, content=None, min=0, max=HUGE, name=None):
assert (0 <= min <= max <= HUGE), (min, max)
if (content is not None):
content = tuple(map(tuple, content))
assert len(content), repr(content)
for alt in content:
... |
def bench_all(repeats, dict_path=None):
logger.debug('loading MorphAnalyzer...')
morph = MorphAnalyzer(dict_path)
morph_plain = MorphAnalyzer(dict_path, result_type=None)
logger.debug('loading benchmark data...')
words = load_words()
total_usages = get_total_usages(words)
logger.debug('Words... |
def _format_fallback_interval(start: _Instant, end: _Instant, skeleton: (str | None), tzinfo: (datetime.tzinfo | None), locale: ((Locale | str) | None)=LC_TIME) -> str:
if (skeleton in locale.datetime_skeletons):
format = (lambda dt: format_skeleton(skeleton, dt, tzinfo, locale=locale))
elif all(((isins... |
class DetectionLoss(nn.Module):
__constants__ = ['num_classes']
def __init__(self, config):
super(DetectionLoss, self).__init__()
self.config = config
self.num_classes = config.num_classes
self.alpha = config.alpha
self.gamma = config.gamma
self.delta = config.del... |
class LabelSmoothSoftmaxCE(nn.Module):
def __init__(self, lb_pos=0.9, lb_neg=0.005, reduction='mean', lb_ignore=255):
super(LabelSmoothSoftmaxCE, self).__init__()
self.lb_pos = lb_pos
self.lb_neg = lb_neg
self.reduction = reduction
self.lb_ignore = lb_ignore
self.log_... |
def MakeRelativePathsInFlagsAbsolute(flags, working_directory):
if (not working_directory):
return list(flags)
new_flags = []
make_next_absolute = False
path_flags = ['-isystem', '-I', '-iquote', '--sysroot=']
for flag in flags:
new_flag = flag
if make_next_absolute:
... |
class FileParser():
def __init__(self, vim: VimClient):
self._vim = vim
async def parse_file_structure(self, file_name: str, vim_patterns: Dict) -> Tree[Position]:
patterns = self._convert_patterns(vim_patterns)
logger.fdebug('Converted pattern {vim_patterns} to {patterns}')
with... |
class Comal80Lexer(RegexLexer):
name = 'COMAL-80'
url = '
aliases = ['comal', 'comal80']
filenames = ['*.cml', '*.comal']
version_added = ''
flags = re.IGNORECASE
_suffix = "\\b(?!['\\[\\]\\\\])"
_identifier = "[a-z]['\\[\\]\\\\\\w]*"
tokens = {'root': [('//.*\\n', Comment.Single), (... |
def _extension_extra_sources():
extra_sources = {'qutip.core.data.matmul': ['qutip/core/data/src/matmul_csr_vector.cpp', 'qutip/core/data/src/matmul_diag_vector.cpp']}
out = collections.defaultdict(list)
for (module, sources) in extra_sources.items():
out[module] = [str(pathlib.Path(source)) for sou... |
def initialise_pretrained_embedding(doc_vocab_size, embedding_dim, embedding_placeholder, name='embedding', trainable=True):
with tf.name_scope(name):
if trainable:
print('init pretrained embds')
embedding_matrix = tf.Variable(embedding_placeholder, trainable=True, name='W', dtype=tf... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.