code stringlengths 101 5.91M |
|---|
def load_user_goal(filename):
data = read_s3_json(S3_BUCKET_NAME, filename)
key = list(data.keys())[0]
return data[key] |
def auto_decode(data):
for (bom, encoding) in BOMS:
if data.startswith(bom):
return data[len(bom):].decode(encoding)
for line in data.split(b'\n')[:2]:
if ((line[0:1] == b'#') and ENCODING_RE.search(line)):
encoding = ENCODING_RE.search(line).groups()[0].decode('ascii')
... |
def test_maxpool1d_padding_valid():
time_dim = Dim(Tensor('time', [batch_dim], dtype='int32'))
in_dim = Dim(7, name='in')
extern_data = TensorDict({'data': Tensor('data', [batch_dim, time_dim, in_dim], dtype='float32')})
class _Net(rf.Module):
def __call__(self, x: rf.Tensor, *, in_spatial_dim: ... |
def save_json(json_file, filename):
with open(filename, 'w') as f:
json.dump(json_file, f, indent=4, sort_keys=False) |
def test_no_branchless_code_object_register_multiple():
tracer = ExecutionTracer()
tracer.register_code_object(MagicMock())
tracer.register_code_object(MagicMock())
tracer.register_predicate(MagicMock(code_object_id=0))
tracer.register_predicate(MagicMock(code_object_id=0))
assert (tracer.get_su... |
def get_mutualinfo_obs_network_args(env, embedding_dim):
network_args = dict(name='mutualinfo_obs_network', input_shape=(embedding_dim,), output_dim=1, hidden_sizes=(64, 64), hidden_nonlinearity=tf.nn.relu, output_nonlinearity=None, batch_normalization=False)
return network_args |
def coco_eval_with_return(result_files, result_types, coco, max_dets=(100, 300, 1000)):
for res_type in result_types:
assert (res_type in ['proposal', 'proposal_fast', 'bbox', 'segm', 'keypoints'])
if mmcv.is_str(coco):
coco = COCO(coco)
assert isinstance(coco, COCO)
if (result_types == ... |
def sample_gumbel(shape, eps=1e-20):
unif = torch.rand(*shape).to(device)
g = (- torch.log((- torch.log((unif + eps)))))
return g |
class RunningAvg(object):
def __init__(self, gamma, init_value=None):
self._value = init_value
self._gamma = gamma
def update(self, new_val):
if (self._value is None):
self._value = new_val
else:
self._value = ((self._gamma * self._value) + ((1.0 - self._g... |
class DecisionTransformerGPT2PreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class BASE_USE(nn.Module):
def __init__(self, img_size=512, in_chans=3, num_stages=4, num_layers=[2, 2, 2, 2], embed_dims=[64, 128, 320, 512], mlp_ratios=[8, 8, 4, 4], num_heads=[8, 8, 8, 8], qkv_bias=True, qk_scale=None, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0, norm_layer=partial(nn.LayerNorm, eps=1e... |
def report_gen(target, data):
target.write('#+\n')
target.write('# The following parameters are assigned with default values. These parameters can\n')
target.write('# be overridden through the make command line\n')
target.write('#+\n')
target.write('\n')
if (('testinfo' in data) and ('profile' i... |
def prefix(*args: str):
global PREFIX_STACK
l = list(map(str, args))
try:
PREFIX_STACK.insert(0, l)
(yield)
finally:
assert (PREFIX_STACK[0] is l)
PREFIX_STACK.pop(0) |
def mk_auto_src():
if (not ONLY_MAKEFILES):
exec_pyg_scripts()
mk_pat_db()
mk_all_install_tactic_cpps()
mk_all_mem_initializer_cpps()
mk_all_gparams_register_modules() |
def bias_variable(shape, name=None):
initial = tf.constant(0.0, shape=shape)
if (name is None):
return tf.Variable(initial)
else:
return tf.get_variable(name, initializer=initial) |
def entity_coverage_with_elq(split):
threshold = (- 5)
dataset = load_json(f'outputs/WebQSP.{split}.expr.json')
linking_result = load_json('misc/webqsp_{}_elq{}_mid.json'.format(split, threshold))
linking_result = dict([(x['id'], x) for x in linking_result])
counted = 0
covered_cnt = 0
equal... |
class WolpertWolf(EntropyEstimator):
def __init__(self, alpha):
super().__init__()
self.alpha = self.check_alpha(alpha)
_function
def fit(self, nk, k=None, zk=None):
if (k is None):
raise NddError('Wolper-Wolf estimator needs k')
if (k == 1):
(self.est... |
def gen_nsml_report(acc_train, aux_out_train, acc_dev, aux_out_dev):
(ave_loss, acc_lx, acc_x) = acc_train
(grad_abs_mean_mean, grad_abs_mean_sig, grad_abs_sig_mean) = aux_out_train
(ave_loss_t, acc_lx_t, acc_x_t) = acc_dev
nsml.report(step=epoch, epoch=epoch, epochs_total=args.tepoch, train__loss=ave_l... |
class BiaffineScorer(nn.Module):
def __init__(self, n_in=800, n_out=400, n_out_label=1, bias_x=True, bias_y=False, scaling=False, dropout=0.33):
super(BiaffineScorer, self).__init__()
self.l = MLP(n_in=n_in, n_out=n_out, dropout=dropout)
self.r = MLP(n_in=n_in, n_out=n_out, dropout=dropout)
... |
class Net(nn.Module):
def __init__(self):
torch.manual_seed(0)
super(Net, self).__init__()
self.model = torchvision.models.mobilenet_v2(pretrained=True)
self.model.requires_grad_(False)
self.model.classifier[1] = torch.nn.Linear(in_features=1280, out_features=200, bias=True)
... |
((not workspace.C.use_mkldnn), 'No MKLDNN support.')
class DropoutTest(hu.HypothesisTestCase):
(X=hu.tensor(), in_place=st.booleans(), ratio=st.floats(0, 0.999), **mu.gcs)
def test_dropout_is_test(self, X, in_place, ratio, gc, dc):
op = core.CreateOperator('Dropout', ['X'], [('X' if in_place else 'Y')],... |
def get_chord_sequence(ev_seq, chord_evs):
ev_seq = [x for x in ev_seq if any(((x in chord_evs[typ]) for typ in chord_evs.keys()))]
legal_seq = []
cnt = 0
for (i, ev) in enumerate(ev_seq):
cnt += 1
if ((ev in chord_evs['Chord-Slash']) and (cnt == 3)):
cnt = 0
lega... |
def reduce_lr_on_platu_step_fn(scheduler: Any, i_iter: int, loss_value: float):
scheduler.step(loss_value) |
class Function_factorial(GinacFunction):
def __init__(self):
GinacFunction.__init__(self, 'factorial', latex_name='{\\rm factorial}', conversions=dict(maxima='factorial', mathematica='Factorial', sympy='factorial', fricas='factorial', giac='factorial'))
def _eval_(self, x):
if isinstance(x, (int... |
def get_param_space(trial):
trial.suggest_float('learning_rate', 0.0001, 0.001, log=True)
trial.suggest_float('lr_decay_rate', 0.7, 1.0, log=True)
trial.suggest_categorical('weight_decay', [1e-06, 1e-07, 0])
trial.suggest_int('layers', 1, 6)
trial.suggest_int('set_layers', 0, 0)
trial.suggest_in... |
class CUDATestBase(DeviceTypeTestBase):
device_type = 'cuda'
_do_cuda_memory_leak_check = True
_do_cuda_non_default_stream = True
primary_device: ClassVar[str]
cudnn_version: ClassVar[Any]
no_magma: ClassVar[bool]
no_cudnn: ClassVar[bool]
def has_cudnn(self):
return (not self.no_... |
def get_caffe_resolver():
global SHARED_CAFFE_RESOLVER
if (SHARED_CAFFE_RESOLVER is None):
SHARED_CAFFE_RESOLVER = CaffeResolver()
return SHARED_CAFFE_RESOLVER |
class TestResNetForward():
.parametrize('layers,planes,output_size', [([1, 1, 1, 1], [16, 32, 14, 8], 8), ([1, 1, 3, 4], [16, 32, 14, 8], 8), ([1, 1, 1, 1], [16, 32, 14, 1], 1), ([1, 1, 1, 1], [16, 32, 14, 8], 8), ([1, 1, 1, 1], [4, 4, 4, 4], 4)])
def test_basicblock_resnets_output_vector_of_correct_size_withou... |
def from_rank(r, n, k):
if (k < 0):
raise ValueError('k must be > 0')
if (k > n):
raise ValueError('k must be <= n')
if ((n == 0) or (k == 0)):
return ()
if (n < 0):
raise ValueError('n must be >= 0')
B = binomial(n, k)
if ((r < 0) or (r >= B)):
raise Valu... |
class Generator(nn.Module):
def __init__(self, w_out, h_out, num_features, num_blocks, code_size):
super(Generator, self).__init__()
pad_w = []
pad_h = []
w = w_out
h = h_out
for i in range((len(num_features) - 1)):
if ((w % 4) == 2):
pad_w... |
def lift_for_SL(A, N=None):
from sage.matrix.special import identity_matrix, diagonal_matrix, block_diagonal_matrix
from sage.misc.misc_c import prod
ring = A.parent().base_ring()
if (N is None):
if (ring is ZZ):
raise ValueError('you must choose the modulus')
else:
... |
def get_pssm_for_file(filename):
scop_id = filename.split('/')[(- 1)].split('.')[0]
pssm_for_scop_id = []
with open(filename, 'r') as f:
lines = f.read().split()
position_mutations = []
for (i, line) in enumerate(lines[2:]):
if (((i % 20) == 0) and (i != 0)):
pssm_for_sco... |
def StarGraph(n):
G = Graph({0: list(range(1, (n + 1)))}, name='Star graph', format='dict_of_lists')
G.set_pos({0: (0, 0)})
G._circle_embedding(list(range(1, (n + 1))), angle=(pi / 2))
return G |
def test_toms748_scan(tmp_path, hypotest_args):
(_, data, model) = hypotest_args
results = pyhf.infer.intervals.upper_limits.toms748_scan(data, model, 0, 5, rtol=1e-08)
assert (len(results) == 2)
(observed_limit, expected_limits) = results
observed_cls = pyhf.infer.hypotest(observed_limit, data, mod... |
def to_f16(t):
return jax.tree_map((lambda x: (x.astype(jnp.float16) if (x.dtype == jnp.float32) else x)), t) |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-train_src', required=True)
parser.add_argument('-train_tgt', required=True)
parser.add_argument('-valid_src', required=True)
parser.add_argument('-valid_tgt', required=True)
parser.add_argument('-save_data', required=True)
... |
class MockGlorotInitializer(Initializer):
def __init__(self):
pass
def __call__(self, shape, dtype=None, partition_info=None, verify_shape=None):
return tf.constant(((np.random.rand(*shape) - 0.5) * 0.0001), dtype=dtype) |
class ExtIndexObject():
def __init__(self, idx_entry: ExtIndex, parameters: 'Parameters', slot: Optional[int]=None) -> None:
self.idx_entry = idx_entry
self._parameters = parameters
self.slot = slot
self.name: Optional[str] = None
(self.type, self.std_idx_entry) = self.conver... |
class InvalidRegularExpression(OperationSchemaError):
__module__ = 'builtins'
def from_hypothesis_jsonschema_message(cls, message: str) -> InvalidRegularExpression:
match = re.search("pattern='(.*?)'.*?\\((.*?)\\)", message)
if match:
message = f'Invalid regular expression. Pattern `... |
class FastRCNNTest(unittest.TestCase):
def test_fast_rcnn(self):
torch.manual_seed(132)
box_head_output_size = 8
box_predictor = FastRCNNOutputLayers(ShapeSpec(channels=box_head_output_size), box2box_transform=Box2BoxTransform(weights=(10, 10, 5, 5)), num_classes=5)
feature_pooled = ... |
def test_visualize_graph_for_single_table():
data = pd.DataFrame({'\\|=/#$324%^,"&*()><...': ['a', 'b', 'c']})
metadata = SingleTableMetadata()
metadata.detect_from_dataframe(data)
model = GaussianCopulaSynthesizer(metadata)
metadata.visualize()
metadata.validate()
model.fit(data)
model.... |
class ScraperSpiderMiddleware(object):
def from_crawler(cls, crawler):
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_spider_input(response, spider):
return None
def process_spider_output(response, result, spider):
... |
def get_test_data(sample_size=1000, embedding_size=4, sparse_feature_num=1, dense_feature_num=1, sequence_feature=['sum', 'mean', 'max'], classification=True, include_length=False, hash_flag=False, prefix=''):
feature_columns = []
model_input = {}
if ('weight' in sequence_feature):
feature_columns.a... |
class TFCvtOutput(tf.keras.layers.Layer):
def __init__(self, config: CvtConfig, embed_dim: int, drop_rate: int, **kwargs):
super().__init__(**kwargs)
self.dense = tf.keras.layers.Dense(units=embed_dim, kernel_initializer=get_initializer(config.initializer_range), name='dense')
self.dropout =... |
def is_response_abstained(generation, fn_type):
if (fn_type == 'perplexity_ai'):
return perplexity_ai_abstain_detect(generation)
elif (fn_type == 'generic'):
return generic_abstain_detect(generation)
else:
return False |
def to_categorical(mask, num_classes, channel='channel_first'):
if ((channel != 'channel_first') and (channel != 'channel_last')):
assert False, "channel should be either 'channel_first' or 'channel_last'"
assert (num_classes > 1), 'num_classes should be greater than 1'
unique = np.unique(mask)
... |
def tv_loss_on_voxel_hash(query, feature, G0=16, growth_factor=1.5, T0=(2 ** 15), L=16, D=2, min_=[(- 1), (- 1), (- 1)], max_=[1, 1, 1], boundary_check=False, ctx=None):
func = TVLossOnVoxelHash(ctx, G0, growth_factor, T0, L, D, min_, max_, boundary_check)
return func(query, feature) |
def extract_value(string, key):
escaped_key = re.escape(key)
pattern = '(?P<key>{})\\s*:\\s*(?P<value>[-+]?\\d*\\.\\d+([eE][-+]?\\d+)?)'.format(escaped_key)
match = re.search(pattern, string)
if match:
value = match.group('value')
return value
else:
return None |
.parametrize('func_module', PARAM_VALIDATION_FUNCTION_LIST)
def test_function_param_validation(func_module):
(module_name, func_name) = func_module.rsplit('.', 1)
module = import_module(module_name)
func = getattr(module, func_name)
func_sig = signature(func)
func_params = [p.name for p in func_sig.... |
def matched(s, c1, c2):
count = 0
for i in s:
if (i == c1):
count += 1
elif (i == c2):
count -= 1
if (count < 0):
return False
return (count == 0) |
class SwitchTransformersForConditionalGeneration(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def max_pool(bottom, ks=2, stride=2):
return L.Pooling(bottom, pool=P.Pooling.MAX, kernel_size=ks, stride=stride) |
.torch
def test_tensor_feature_setters(some_num_tensor_feature, some_cat_tensor_feature):
some_num_tensor_feature._set_feature_hint(FeatureHint.RATING)
some_num_tensor_feature._set_feature_sources([TensorFeatureSource(FeatureSource.INTERACTIONS, 'fake1')])
some_num_tensor_feature._set_tensor_dim(42)
som... |
def show_image_labels(image, label, img, lbl):
images = torch.cat([image, img], dim=2)
labels = torch.cat([label, lbl], dim=2)
image_labels = torch.cat([images, labels], dim=1)
image_labels = Image.fromarray(image_labels.permute(1, 2, 0).numpy())
return image_labels |
class FunctionalExpression():
def __init__(self, parts):
self.parts = tuple(parts)
def dump(self, indent=' '):
print(('%s%s' % (indent, self._dump())))
for part in self.parts:
part.dump((indent + ' '))
def _dump(self):
return self.__class__.__name__
def inst... |
class SpecifierSet(BaseSpecifier):
def __init__(self, specifiers='', prereleases=None):
specifiers = [s.strip() for s in specifiers.split(',') if s.strip()]
parsed = set()
for specifier in specifiers:
try:
parsed.add(Specifier(specifier))
except Invali... |
def register_Ns3MgtAssocResponseHeader_methods(root_module, cls):
cls.add_constructor([param('ns3::MgtAssocResponseHeader const &', 'arg0')])
cls.add_constructor([])
cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True)
cls.add_method('GetCapabilities', 'n... |
def test_two_connectivity_holes():
expected = np.array([[0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 1, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1]], boo... |
def build_tfrecord_input(training=True):
filenames = gfile.Glob(os.path.join(FLAGS.data_dir, '*'))
if (not filenames):
raise RuntimeError('No data files found.')
index = int(np.floor((FLAGS.train_val_split * len(filenames))))
if training:
filenames = filenames[:index]
else:
f... |
class ImageFolderCustomClass(data.Dataset):
def __init__(self, root, transform=None, target_transform=None, loader=default_loader, custom_class_to_idx=None):
if (custom_class_to_idx is None):
(classes, class_to_idx) = find_classes(root)
else:
class_to_idx = custom_class_to_id... |
class ConditionGen(nn.Module):
def __init__(self, z_dim, nlabels, embed_size=256):
super().__init__()
self.embedding = nn.Embedding(nlabels, embed_size)
self.latent_dim = (z_dim + embed_size)
self.z_dim = z_dim
self.nlabels = nlabels
self.embed_size = embed_size
d... |
def _format(val: Any, output_format: str='standard', errors: str='coarse') -> Any:
val = str(val)
result: Any = []
if (val in NULL_VALUES):
return [np.nan]
if (not validate_mc_tva(val)):
if (errors == 'raise'):
raise ValueError(f'Unable to parse value {val}')
error_re... |
class LxmertTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__(self, vocab_file, do_low... |
class Block(nn.Module):
def __init__(self, in_ch, out_ch, h_ch=None, ksize=3, pad=1, activation=F.relu, upsample=False, num_classes=0):
super(Block, self).__init__()
self.activation = activation
self.upsample = upsample
self.learnable_sc = ((in_ch != out_ch) or upsample)
if (... |
def _get_keys_from_observation_space(observation_space: GymnasiumDictSpace) -> Sequence[str]:
return sorted(list(observation_space.keys())) |
def _calc_df_coefficient_C_l1_l2_Taylor_coeff(l1, l2, p1, p2, derivs_list):
tot = 0
l1fact_inv = (1 / factorial(l1))
l2fact_inv = (1 / factorial(l2))
prefactor = (l1fact_inv * l2fact_inv)
for m1 in range((l1 + 1)):
for r1 in range(((l1 - m1) + 1)):
for m2 in range((l2 + 1)):
... |
class Ok(Generic[T]):
__slots__ = ('_value',)
def __init__(self, value: T):
self._value = value
def ok(self) -> T:
return self._value |
def get_lisp_from_graph_query(graph_query):
G = nx.MultiDiGraph()
aggregation = 'none'
arg_node = None
for node in graph_query['nodes']:
G.add_node(node['nid'], id=node['id'], type=node['node_type'], question=node['question_node'], function=node['function'], cla=node['class'])
if (node['... |
def get_new_exemplars(dict_of_features, normalised_features_dict, dict_of_means, exemp_size_dict):
overlapping_exemplars_indices = get_overlap_region_exemplars(normalised_features_dict)
overlapping_exemplars = {label: np.array(features)[overlapping_exemplars_indices[label][:exemp_size_dict[label]]] for (label, ... |
def test_check_clustering_error():
rng = np.random.RandomState(42)
noise = rng.rand(500)
wavelength = (np.linspace(0.01, 1, 500) * 1e-06)
msg = 'Clustering metrics expects discrete values but received continuous values for label, and continuous values for target'
with pytest.warns(UserWarning, match... |
class ResNet101(nn.Module):
def __init__(self, block, layers, num_classes, BatchNorm, bn_clr=False):
self.inplanes = 64
self.bn_clr = bn_clr
super(ResNet101, self).__init__()
self.ce_loss = nn.CrossEntropyLoss(ignore_index=IGNORE_LABEL)
self.conv1 = nn.Conv2d(3, 64, kernel_si... |
def train(train_loader, models, CE, optimizers, epoch, logger, logging):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
for m in models:
m.train()
end = time.time()
for (i, (inputs, target)) in enumerate(train_loader):
global_s... |
def register_Ns3RrComponentCarrierManager_methods(root_module, cls):
cls.add_constructor([param('ns3::RrComponentCarrierManager const &', 'arg0')])
cls.add_constructor([])
cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True)
cls.add_method('DoReportBufferStatus', 'void', [param('ns3::LteMacSap... |
def auread(path, channel_first=False, raw_format_param=None, **kwargs):
from nnabla.utils.data_source_loader import ResourceFileReader
source = ResourceFileReader(path)
return backend_manager.module.auread(source, channel_first=channel_first, raw_format_param=None, **kwargs) |
def test_broadcast_float_int_union():
this = ak.contents.NumpyArray(np.arange(4), parameters={'name': 'this'})
that_1 = ak.contents.ByteMaskedArray(ak.index.Index8(np.array([0, 1, 0, 1], dtype='int8')), ak.contents.NumpyArray(np.arange(4)), valid_when=True, parameters={'name': 'that'})
that_2 = ak.contents.... |
class Cartpole(_Cartpole):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.episode_id = 0
self.episode_return = 0
self.bsuite_id = 'cartpole/0'
def reset(self) -> dm_env.TimeStep:
self.episode_id += 1
self.episode_retu... |
def score_nights_dataset(model, test_loader, device):
logging.info('Evaluating NIGHTS dataset.')
d0s = []
d1s = []
targets = []
with torch.no_grad():
for (i, (img_ref, img_left, img_right, target, idx)) in tqdm(enumerate(test_loader), total=len(test_loader)):
(img_ref, img_left, ... |
()
def test_write_file(file_system_agents: List[Agent], patched_api_requestor: None, monkeypatch: pytest.MonkeyPatch, level_to_run: int, challenge_name: str) -> None:
file_system_agent = file_system_agents[(level_to_run - 1)]
run_interaction_loop(monkeypatch, file_system_agent, CYCLE_COUNT_PER_LEVEL[(level_to_r... |
_pytesseract
_tokenizers
class LayoutLMv2ProcessorTest(unittest.TestCase):
tokenizer_class = LayoutLMv2Tokenizer
rust_tokenizer_class = LayoutLMv2TokenizerFast
def setUp(self):
vocab_tokens = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', '... |
def _seg_26():
return [(11472, 'M', u''), (11473, 'V'), (11474, 'M', u''), (11475, 'V'), (11476, 'M', u''), (11477, 'V'), (11478, 'M', u''), (11479, 'V'), (11480, 'M', u''), (11481, 'V'), (11482, 'M', u''), (11483, 'V'), (11484, 'M', u''), (11485, 'V'), (11486, 'M', u''), (11487, 'V'), (11488, 'M', u''), (11489, 'V... |
class Length(object):
def __init__(self, min=(- 1), max=(- 1), message=None):
assert ((min != (- 1)) or (max != (- 1))), 'At least one of `min` or `max` must be specified.'
assert ((max == (- 1)) or (min <= max)), '`min` cannot be more than `max`.'
self.min = min
self.max = max
... |
.parametrize('decorators, expected', [pytest.param('property', False), pytest.param(['property', 'contextmanager'], True)])
def test__has_decorator(comments_tree, decorators, expected):
public_function = get_function_node_from_ast(comments_tree, 'public_function')
assert (has_decorator(astroid_to_ast(public_fun... |
def build_rnnt(num_classes: int, input_dim: int, num_encoder_layers: int=4, num_decoder_layers: int=1, encoder_hidden_state_dim: int=320, decoder_hidden_state_dim: int=512, output_dim: int=512, rnn_type: str='lstm', bidirectional: bool=True, encoder_dropout_p: float=0.2, decoder_dropout_p: float=0.2, sos_id: int=1, eos... |
def Get_dataloader(path, batch):
transforms_ = [transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]
train_dataloader = DataLoader(ImageDataset(path, transforms_=transforms_), batch_size=batch, shuffle=True, num_workers=2, drop_last=True)
return train... |
def parse_inputs(args):
try:
filename = args[1]
lamb = float(args[2])
alpha = float(args[3])
gamma = float(args[4])
max_norm = float(args[5])
max_steps = int(args[6])
(X, Y) = ([], [])
with open(filename) as f:
for line in f:
... |
class BModel():
def __init__(self, bmodel_file):
with bmodel_context(self):
self.head = None
binary_desc = None
binary = None
self.file_name = bmodel_file
with open(bmodel_file, 'rb') as file_obj:
file_obj.seek(0, 0)
... |
def l2_loss(pred, target, reduction='mean'):
assert ((pred.size() == target.size()) and (target.numel() > 0))
assert (pred.size()[0] == target.size()[0])
batch_size = pred.size()[0]
loss = torch.norm((pred - target).view(batch_size, (- 1)), p=2, dim=1, keepdim=True)
if (reduction == 'mean'):
... |
class MaximumAngleCalculator(MeshQualityCalculator):
def compute(self, mesh: fenics.Mesh) -> np.ndarray:
comm = mesh.mpi_comm()
ghost_offset = mesh.topology().ghost_offset(mesh.topology().dim())
maximum_angle_array = self._quality_object.maximum_angle(mesh).array()[:ghost_offset]
max... |
class BdfFontFile(FontFile.FontFile):
def __init__(self, fp):
super().__init__()
s = fp.readline()
if (s[:13] != b'STARTFONT 2.1'):
raise SyntaxError('not a valid BDF file')
props = {}
comments = []
while True:
s = fp.readline()
if ... |
def write_temp_2tag(filename, bio_data):
doc = []
sentences = bio_data.split('\n\n')
for sentence in sentences:
doc.append([])
for word in sentence.split('\n'):
(text, tags) = word.split('\t', maxsplit=1)
doc[(- 1)].append({'text': text, 'multi_ner': tags.split()})
... |
_builder('textcaps_caption')
class TextCapsCapBuilder(BaseDatasetBuilder):
train_dataset_cls = TextCapsCapDataset
eval_dataset_cls = TextCapsCapEvalDataset
DATASET_CONFIG_DICT = {'default': 'configs/datasets/textcaps/defaults.yaml'} |
class PairBasicEvaluator(BasicEvaluator):
def evaluate(self, predict, ground_truth):
predict = [x for x in predict if (x != STEP_IDX)]
ground_truth = [x for x in ground_truth if (x != STEP_IDX)]
return super().evaluate(predict, ground_truth) |
def hashing_trick(word, n, hash_function=None):
if (hash_function is None):
hash_function = hash
elif (hash_function == 'md5'):
hash_function = (lambda w: int(md5(w.encode()).hexdigest(), 16))
return ((hash_function(word) % (n - 1)) + 1) |
def move_billing_codes(patient: RawPatient) -> RawPatient:
visit_starts: Dict[(int, datetime.datetime)] = {}
visit_ends: Dict[(int, datetime.datetime)] = {}
tables_w_billing_codes: List[str] = ['condition_occurrence', 'procedure_occurrence', 'observation']
for event in patient.events:
if ((event... |
def resnet152_retinanet(num_classes, inputs=None, **kwargs):
return resnet_retinanet(num_classes=num_classes, backbone='resnet152', inputs=inputs, **kwargs) |
class TestCoder(unittest.TestCase):
def test_coder_can_io(self):
data = make_data()
builder = make_code_builder(data)
coder = builder.build_code()
with NamedTemporaryFile() as tmp_fp:
coder.to_file(tmp_fp.name)
other_coder = HuffmanCoder.from_file(tmp_fp.name)... |
def inception_v1_base(inputs, final_endpoint='Mixed_5c', scope='InceptionV1'):
end_points = {}
with tf.variable_scope(scope, 'InceptionV1', [inputs]):
with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_initializer=trunc_normal(0.01)):
with slim.arg_scope([slim.conv2d, slim.max_... |
def normalize(audio, target_level=(- 25)):
rms = ((audio ** 2).mean() ** 0.5)
scalar = ((10 ** (target_level / 20)) / (rms + EPS))
audio = (audio * scalar)
return audio |
def normalize_adj_torch(adj):
if (len(adj.size()) == 4):
new_r = torch.zeros(adj.size()).type_as(adj)
for i in range(adj.size(1)):
adj_item = adj[(0, i)]
rowsum = adj_item.sum(1)
d_inv_sqrt = rowsum.pow_((- 0.5))
d_inv_sqrt[torch.isnan(d_inv_sqrt)] = 0... |
def _get_video_feat_by_vid(_feat_dir, vid):
_feat_path = os.path.join(_feat_dir, f'{vid}.npz')
_feat = np.load(_feat_path)['features'].astype(np.float32)
_feat = l2_normalize_np_array(_feat)
return _feat |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.