code stringlengths 101 5.91M |
|---|
class BertDictionary(MaskedLMDictionary):
def __init__(self, pad='<pad>', eos='</s>', unk='<unk>', mask='<mask>', cls='<cls>', sep='<sep>'):
super().__init__(pad, eos, unk, mask)
self.cls_word = cls
self.sep_word = sep
self.cls_index = self.add_symbol(cls)
self.sep_index = se... |
class WeightedIntegerVectors_all(DisjointUnionEnumeratedSets):
def __init__(self, weight):
self._weights = weight
from sage.sets.family import Family
from sage.sets.non_negative_integers import NonNegativeIntegers
from functools import partial
F = Family(NonNegativeIntegers()... |
class StatsFileFramerateMismatch(Exception):
def __init__(self, base_timecode_fps, stats_file_fps, message='Framerate differs between stats file and base timecode.'):
super(StatsFileFramerateMismatch, self).__init__(message)
self.base_timecode_fps = base_timecode_fps
self.stats_file_fps = st... |
def ground(statement_path, cpnet_vocab_path, pattern_path, output_path, num_processes=1, debug=False):
global PATTERN_PATH, CPNET_VOCAB
if (PATTERN_PATH is None):
PATTERN_PATH = pattern_path
CPNET_VOCAB = load_cpnet_vocab(cpnet_vocab_path)
sents = []
answers = []
with open(statement_... |
_experiment
def vpg_pendulum(ctxt=None, seed=1):
set_seed(seed)
env = GarageEnv(env_name='InvertedDoublePendulum-v2')
runner = LocalRunner(ctxt)
policy = GaussianMLPPolicy(env.spec, hidden_sizes=[64, 64], hidden_nonlinearity=torch.tanh, output_nonlinearity=None)
value_function = GaussianMLPValueFunc... |
def export_onnx_model(model, inputs):
assert isinstance(model, torch.nn.Module)
def _check_eval(module):
assert (not module.training)
model.apply(_check_eval)
with torch.no_grad():
with io.BytesIO() as f:
torch.onnx.export(model, inputs, f, operator_export_type=OperatorExport... |
(scope='module')
def dev_file_with_trees(tmp_path_factory):
dev_set = (DATASET_WITH_TREES * 2)
dev_filename = (tmp_path_factory.mktemp('data') / 'dev_trees.json')
with open(dev_filename, 'w', encoding='utf-8') as fout:
json.dump(dev_set, fout, ensure_ascii=False)
return dev_filename |
class AdaptiveAvgPool3d(_AdaptiveAvgPoolNd):
output_size: _size_3_t
def forward(self, input: Tensor) -> Tensor:
return F.adaptive_avg_pool3d(input, self.output_size) |
def get_qas(text):
out = subprocess.check_output(['from_question_generation/get_qnas', text])
questions = [line.split('\t') for line in str(out, 'utf-8').split('\n')]
factoid_qas = [{'question': e[0], 'answer': e[1], 'score': e[2]} for e in questions if (len(e) == 3)]
return factoid_qas |
class Edge(SageObject):
def __init__(self, p, label, rep, origin, target, links=None, opposite=None, determinant=None, valuation=None):
if (links is None):
links = []
if (determinant is None):
determinant = rep.determinant()
if (valuation is None):
valuati... |
def test_extract_nodes():
modela = ModelA()
modelb = ModelB()
modela.ref_field = modelb
modela.ref_field2 = 'user_set_name'
model_list = []
io._extract_nodes(modela, model_list)
assert (len(model_list) == 2)
assert (modela in model_list)
assert (modelb in model_list) |
def manually_copy_vissl_head(from_state_dict, to_state_dict, keys: List[Tuple[(str, str)]]):
for (from_key, to_key) in keys:
to_state_dict[to_key] = from_state_dict[from_key].clone()
print(f'Copied key={from_key} to={to_key}')
return to_state_dict |
def stack_fn(x):
x = stack1(x, 64, 3, name='conv2')
x = stack1(x, 128, 4, name='conv3')
x = stack1(x, 256, 6, name='conv4')
return stack1(x, 512, 3, name='conv5') |
def get_pattern(query):
pattern = '^'
for res in query:
assert (res in known_abbrev), ('# Fatal error: character %s not known. Use AUCG/NYRSWKMBDHV' % res)
if (res in rna):
pattern += res
else:
if (res == 'N'):
pattern += '[AUCGT]'
if (... |
def get_df_info(df: pd.DataFrame):
print(f'Total rows {len(df)}, unique users: {df.user_id.nunique()}, unique items: {df.item_id.nunique()}') |
def create_feature_columns() -> Tuple[(list, list, list)]:
(first_order_feature_columns, second_order_feature_columns, label_feature_columns) = ([], [], [])
userid = fc.categorical_column_with_vocabulary_file('userid', os.path.join(FLAGS.vocabulary_dir, 'userid.txt'))
feedid = fc.categorical_column_with_voc... |
def infer(info, input_data):
class tmp():
pass
args = tmp
tmp.outdir = ''
tmp.result_outdir = ''
class ForwardConfig():
pass
config = ForwardConfig
config.executors = info.executors.values()
config.networks = []
for e in config.executors:
if (e.network.name in... |
def generate(template: Template, **kwargs) -> Callable:
if hasattr(dsp.settings, 'inspect'):
inspector = dsp.settings.inspect
_generate = inspector.inspect_func(dsp.predict._generate)
return _generate(template, **kwargs)
else:
return dsp.predict._generate(template, **kwargs) |
class T5TokenizerFast(metaclass=DummyObject):
_backends = ['tokenizers']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tokenizers']) |
def get_format_strings(kv_pairs):
log_strings = []
for (key, value) in kv_pairs:
fmt = get_print_format(value)
format_string = (('{}: {:' + fmt) + '}')
log_strings.append(format_string.format(key, value))
return log_strings |
class Empty(LayoutBuilder):
def __init__(self):
self._init(None)
def __repr__(self):
return 'ak.numba.lb.Empty(parameters=None)'
def numbatype(self):
import numba
return ak._connect.numba.layoutbuilder.EmptyType(numba.types.StringLiteral(None))
def __len__(self):
... |
def tukeylambda_kurtosis(lam):
lam = np.asarray(lam)
shp = lam.shape
lam = np.atleast_1d(lam).astype(np.float64)
threshold = 0.055
low_mask = (lam < (- 0.25))
negqrtr_mask = (lam == (- 0.25))
small_mask = (np.abs(lam) < threshold)
reg_mask = (~ ((low_mask | negqrtr_mask) | small_mask))
... |
class Config():
def __init__(self) -> None:
self.val_measures = {'Emax': {'CoCA': 0.783, 'CoSOD3k': 0.874, 'CoSal2015': 0.892}, 'Smeasure': {'CoCA': 0.71, 'CoSOD3k': 0.81, 'CoSal2015': 0.838}, 'Fmax': {'CoCA': 0.598, 'CoSOD3k': 0.805, 'CoSal2015': 0.856}}
self.validation = True |
class MSVDQADataModule(BaseDataModule):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def dataset_cls(self):
return MSVDQADataset
def dataset_name(self):
return 'msvdqa'
def setup(self, stage):
super().setup(stage)
self.answer2id = self.tr... |
class Point(survey.BaseRx):
def __init__(self, locations, components='gz', **kwargs):
super(Point, self).__init__(locations, **kwargs)
if isinstance(components, str):
components = [components]
for component in components:
validate_string('component', component, ['gx',... |
class CudaBuffer():
def __init__(self, id, target=GL_RENDERBUFFER, flags=pycuda.gl.graphics_map_flags.NONE):
self.cuda_buffer = pycuda.gl.RegisteredImage(id, target, flags)
self.cuda_buffer_map = self.cuda_buffer.map()
def copy_to_tensor(self, tensor):
(h, w, c) = tensor.shape
co... |
def concatenate_images(ic):
all_images = [image[(np.newaxis, ...)] for image in ic]
try:
array_cat = np.concatenate(all_images)
except ValueError:
raise ValueError('Image dimensions must agree.')
return array_cat |
class TestRoot():
def test_tol_parameter(self):
def func(z):
(x, y) = z
return np.array([((x ** 3) - 1), ((y ** 3) - 1)])
def dfunc(z):
(x, y) = z
return np.array([[(3 * (x ** 2)), 0], [0, (3 * (y ** 2))]])
for method in ['hybr', 'lm', 'broyden... |
_config
def task_finetune_ind_itc_irtr_activitynet_randaug():
exp_name = 'finetune_itc_irtr_activitynet_randaug'
datasets = ['activitynet']
train_transform_keys = ['pixelbert_randaug']
loss_names = _loss_names({'ind_itc': 1})
batch_size = 1024
max_epoch = 200
max_steps = None
warmup_step... |
def test_spinner_initializes_with_default_values():
with Spinner() as spinner:
assert (spinner.message == 'Loading...')
assert (spinner.delay == 0.1) |
class DataLoader(torch.utils.data.DataLoader):
def __init__(self, vocab_json, kb_pt, question_pt, batch_size, training=False):
vocab = load_vocab(vocab_json)
inputs = []
with open(question_pt, 'rb') as f:
for _ in range(3):
inputs.append(pickle.load(f))
wi... |
class AlbertForMultipleChoice(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def consolidate_edges(sdfg: SDFG, starting_scope=None) -> int:
from dace.sdfg.propagation import propagate_memlets_scope
total_consolidated = 0
for state in sdfg.states():
if (starting_scope and (starting_scope.entry not in state.nodes())):
continue
queue = ([starting_scope] if s... |
def require_torch_tpu(test_case):
if (not _torch_tpu_available):
return unittest.skip('test requires PyTorch TPU')
else:
return test_case |
def test_preprocess():
root_path = 'tests/data/dataset_sample'
output_path = '/tmp/preprocessed_npzs'
os.makedirs(output_path, exist_ok=True)
PW3D_ROOT = osp.join(root_path, 'pw3d')
cfg = dict(type='Pw3dConverter', modes=['train', 'test'])
data_converter = build_data_converter(cfg)
data_conv... |
def DM_55_7_1():
from sage.rings.finite_rings.integer_mod_ring import IntegerModRing as AdditiveCyclic
G = AdditiveCyclic(55)
M = [[1, 7, 14, 19, 28, 33, 40, 46, 50], [2, 13, 25, 38, 52, 12, 20, 32, 45], [39, 6, 8, 26, 24, 51, 11, 34, 37], [54, 48, 41, 36, 27, 22, 15, 9, 5], [53, 42, 30, 17, 3, 43, 35, 23, ... |
class TAtomicPredicate(object):
thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
_snap.TAtomicPredicate_swiginit(self, _snap.new_TAtomicPredicate(*args))
__swig_destroy__ = _snap.delete_TA... |
class SPADEDataset(BaseDataset):
def __init__(self, opt):
super(SPADEDataset, self).__init__(opt)
self.initialize(opt)
def modify_commandline_options(parser, is_train):
parser.add_argument('--no_pairing_check', action='store_true', help='If specified, skip sanity check of correct label-i... |
class BertPredictionHeadTransform(nn.Module):
def __init__(self, config):
super(BertPredictionHeadTransform, self).__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.transform_act_fn = (ACT2FN[config.hidden_act] if isinstance(config.hidden_act, str) else config.hi... |
def multiset_permutation_next_lex(l):
i = (len(l) - 2)
while ((i >= 0) and (l[i] >= l[(i + 1)])):
i -= 1
if (i <= (- 1)):
return 0
j = (len(l) - 1)
while (l[j] <= l[i]):
j -= 1
(l[i], l[j]) = (l[j], l[i])
l[(i + 1):] = l[:i:(- 1)]
return 1 |
class SymmetricFunctionAlgebra_orthotriang(sfa.SymmetricFunctionAlgebra_generic):
class Element(sfa.SymmetricFunctionAlgebra_generic.Element):
pass
def __init__(self, Sym, base, scalar, prefix, basis_name, leading_coeff=None):
self._sym = Sym
self._sf_base = base
self._scalar = s... |
def plot_alignment(alignment, labels, filename=None):
num_labels = len(labels)
num_frames = len(alignment)
ts = range(num_frames)
if isinstance(alignment[0], list):
assert (len(alignment[0]) == num_labels)
ss = numpy.array(alignment).transpose()
assert (ss.shape == (num_labels, n... |
.parametrize('curr_arch', supported_archs_offline_cache)
def test_closing_offline_cache(curr_arch):
for (kernel, args, get_res) in simple_kernels_to_test:
_test_closing_offline_cache_for_a_kernel(curr_arch=curr_arch, kernel=kernel, args=args, result=get_res(*args)) |
class ResNetV1(nn.Module):
def __init__(self, initial_filters, block, layers, input_channels=1):
self.inplanes = initial_filters
self.num_layers = len(layers)
super(ResNetV1, self).__init__()
self.conv1 = nn.Conv2d(input_channels, initial_filters, kernel_size=7, stride=2, padding=3, ... |
class MyTestClass():
classvalue = 2
def __init__(self, n=5) -> None:
self.n = n
def method_jit(self, A):
return (A + self.n)
def method(self, A: dace.float64[20]):
return (A + self.n)
def __call__(self, A: dace.float64[20]):
return (A * self.n)
def other_method_ca... |
def test_case99():
url = (brokerIp + '/ngsi-ld/v1/entityOperations/upsert')
headers = {'Content-Type': 'application/json', 'Accept': 'application/ld+json', 'Link': '<{{link}}>; rel=" type="application/ld+json"'}
r = requests.post(url, data=json.dumps(ld_data.subdata99), headers=headers)
print(r.content)... |
_type
class Image():
def serialize(image):
import cv2
return cv2.imencode('.png', image)
def deserialize(encoded_image):
import cv2
return cv2.imdecode(np.frombuffer(encoded_image, dtype=np.dtype(np.uint8)), cv2.IMREAD_COLOR) |
def load_old_G():
with open(paths_config.stylegan2_ada_shhq, 'rb') as f:
old_G = pickle.load(f)['G_ema'].to(global_config.device).eval()
old_G = old_G.float()
return old_G |
def prune_linear_layer(layer: nn.Linear, index: torch.LongTensor, dim: int=0) -> nn.Linear:
index = index.to(layer.weight.device)
W = layer.weight.index_select(dim, index).clone().detach()
if (layer.bias is not None):
if (dim == 1):
b = layer.bias.clone().detach()
else:
... |
def train(train_loader, dev_loader, model, args):
if (args.optimizer == 'Adam'):
optimizer = optim.Adam(model.parameters(), lr=args.lr)
elif (args.optimizer == 'SGD'):
optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=0.9)
elif (args.optimizer == 'ASGD'):
optimizer = opt... |
class MaxSoftmaxModel(ModelTemplate):
def __init__(self, base_model, use_softmax=False):
super(ModelTemplate, self).__init__()
self.base_model = base_model
self.use_softmax = use_softmax
def forward(self, imgs):
closed_set_preds = self.base_model(imgs)
if self.use_softmax... |
def test_keras_predictor_raises_on_sample_call() -> None:
model = _DummyKerasPredictor()
with pytest.raises(NotImplementedError):
model.sample(empty_dataset([1], [1]).query_points, 1) |
def test_suite_chop():
trunc = pp.ExceptionTruncation()
chromosome = MagicMock()
suite = MagicMock(test_case_chromosomes=[chromosome, chromosome])
trunc.visit_test_suite_chromosome(suite)
chromosome.accept.assert_has_calls([call(trunc), call(trunc)]) |
def get_dataset_base_dacs(include_diffusion_data, source, target, evalScale):
if (not include_diffusion_data):
if evalScale:
dacs_dataset_base = f'_base_/datasets/uda_{source}_to_{target}_maskrcnn_panoptic_evalScale_{evalScale}.py'
else:
dacs_dataset_base = f'_base_/datasets/... |
class DataCollatorCTCWithPadding():
processor: Wav2Vec2Processor
padding: Union[(bool, str)] = True
max_length: Optional[int] = None
max_length_labels: Optional[int] = None
pad_to_multiple_of: Optional[int] = None
pad_to_multiple_of_labels: Optional[int] = None
def __call__(self, features: L... |
def _instrument(sdfg: dace.SDFG, instr: dace.DataInstrumentationType, ignore: Optional[str]=None):
for (node, _) in sdfg.all_nodes_recursive():
if isinstance(node, nodes.AccessNode):
if (ignore and (ignore in node.data)):
node.instrument = dace.DataInstrumentationType.No_Instrume... |
class ReLU6(Module):
def __init__(self, inplace=False):
super(ReLU6, self).__init__()
self.inplace = inplace
def updateOutput(self, input):
self._backend.HardTanh_updateOutput(self._backend.library_state, input, self.output, 0, 6, self.inplace)
return self.output
def updateGr... |
def remove_node_between_two_nodes(graph: Graph, node_to_remove: BaseNode, first_node: BaseNode, last_node: BaseNode):
e_attr = graph.get_edge_data(first_node, node_to_remove)
assert (len(list(e_attr.values())) == 1)
e_attr = list(e_attr.values())[0]
graph.add_edge(first_node, last_node, **e_attr)
gr... |
class SawyerDoorOpenV1Policy(Policy):
_fully_parsed
def _parse_obs(obs):
return {'hand_pos': obs[:3], 'door_pos': obs[3:6], 'unused_info': obs[6:]}
def get_action(self, obs):
o_d = self._parse_obs(obs)
action = Action({'delta_pos': np.arange(3), 'grab_effort': 3})
action['del... |
def tlarray(A: dace.int32[128]):
tmp = dace.ndarray([128], dace.int32, storage=dace.StorageType.CPU_ThreadLocal)
for i in dace.map[0:128]:
with dace.tasklet:
t = omp_get_thread_num()
(t >> tmp[i])
for i in dace.map[0:128]:
with dace.tasklet:
(t << tmp[i])
... |
def test_all_labels():
for label in LABELS:
assert (decode(b'', label) == ('', lookup(label)))
assert (encode('', label) == b'')
for repeat in [0, 1, 12]:
(output, _) = iter_decode(([b''] * repeat), label)
assert (list(output) == [])
assert (list(iter_enco... |
def download_url_to_file(url, dst, hash_prefix=None, progress=True):
file_size = None
req = Request(url, headers={'User-Agent': 'torch.hub'})
u = urlopen(req)
meta = u.info()
if hasattr(meta, 'getheaders'):
content_length = meta.getheaders('Content-Length')
else:
content_length =... |
def discriminator_loss(disc_real_output, disc_generated_output):
real_loss = loss(tf.ones_like(disc_real_output), disc_real_output)
generated_loss = loss(tf.zeros_like(disc_generated_output), disc_generated_output)
total_disc_loss = (real_loss + generated_loss)
return total_disc_loss |
class CfgNode(dict):
IMMUTABLE = '__immutable__'
DEPRECATED_KEYS = '__deprecated_keys__'
RENAMED_KEYS = '__renamed_keys__'
NEW_ALLOWED = '__new_allowed__'
def __init__(self, init_dict: Optional[dict]=None, key_list: Optional[list]=None, new_allowed: Optional[bool]=False):
init_dict = ({} if ... |
def _get_disc_decomp():
from torch._decomp import get_decompositions
aten = torch.ops.aten
decompositions_dict = get_decompositions([aten.var_mean, aten._adaptive_avg_pool2d_backward, aten.addcmul, aten.avg_pool2d_backward, aten.binary_cross_entropy_with_logits, aten.gelu, aten.gelu_backward, aten.glu_backw... |
def test_option_unknown_2_parm():
text = 'option[unknown, parameters={"foo": "bar"}]'
parsedtype = ak.types.from_datashape(text, highlevel=False)
assert isinstance(parsedtype, ak.types.OptionType)
assert (str(parsedtype) == text) |
def register_Ns3HashFunctionMurmur3_methods(root_module, cls):
cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')])
cls.add_constructor([])
cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('std::size_t const', 'size')], is_virtual=True)
cls.add_meth... |
class VGGM_conv5_body(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 96, (7, 7), (2, 2))
self.relu1 = nn.ReLU(True)
self.norm1 = SpatialCrossMapLRN(5, 0.0005, 0.75, 2)
self.pool1 = nn.MaxPool2d((3, 3), (2, 2), (0, 0), ceil_mode=True)
self... |
class HyperbolicGeodesicUHP(HyperbolicGeodesic):
def reflection_involution(self):
(x, y) = (real(k.coordinates()) for k in self.ideal_endpoints())
if (x == infinity):
M = matrix([[1, ((- 2) * y)], [0, (- 1)]])
elif (y == infinity):
M = matrix([[1, ((- 2) * x)], [0, (-... |
def cook_test(test, ref_len_counts, eff=None, n=4):
(reflen, refmaxcounts) = ref_len_counts
(testlen, counts) = precook(test, n, True)
result = {}
if (eff == 'closest'):
result['reflen'] = min(((abs((l - testlen)), l) for l in reflen))[1]
else:
result['reflen'] = reflen
result['t... |
class DeiTModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def test_mha_exhaustive():
Bs = [1, 2, 4, 8]
SNs = [512, 1024, 2048]
SMs = [512, 1024, 2048]
Hs = [16, 20, 24, 32]
Ps = [64, 96, 128, 192, 384]
compiled_sdfg = create_attn_forward_and_compile(iters=True)
for SM in SMs:
for (B, SN, H, P) in itertools.product(Bs, SNs, Hs, Ps):
... |
def _remove_stopwords(text: Any, stopwords: Optional[Set[str]]=None) -> Any:
if pd.isna(text):
return text
stopwords = (english_stopwords if (not stopwords) else stopwords)
return ' '.join((word for word in str(text).split() if (word.lower() not in stopwords))) |
_utils.test()
def test_func_no_return():
with pytest.raises(ti.TaichiCompilationError, match='Function has a return type but does not have a return statement'):
def bar() -> ti.i32:
pass
def foo() -> ti.i32:
return bar()
foo() |
def bool_(string):
if (string == 'True'):
return True
elif (string == 'False'):
return False
else:
raise Exception(('Cannot cast %r to bool value.' % string)) |
def test_multiple_and_proofs(params):
(p1, p2, secrets_dict) = params
and_proof = AndProofStmt(p1, p2, p2, p1, p1, p1, p2)
prover = and_proof.get_prover(secrets_dict)
verifier = and_proof.get_verifier()
assert verify(verifier, prover) |
class TraceMethodCallMeta(type):
def __init__(self, name, bases, dict):
for (func_name, func) in dict.items():
if inspect.isfunction(func):
setattr(self, func_name, print_on_call_decorator(func)) |
def create_feature_columns() -> Tuple[(list, list, list)]:
(category_feature_columns, dense_feature_columns) = ([], [])
label_feature_columns = []
videoplayseconds = fc.numeric_column('videoplayseconds', default_value=0.0)
u_read_comment_7d_sum = fc.numeric_column('u_read_comment_7d_sum', default_value=... |
def get_oss_binary_file(test_name: str, test_type: TestType) -> str:
assert (test_type in {TestType.CPP, TestType.PY})
binary_folder = get_oss_binary_folder(test_type)
binary_file = os.path.join(binary_folder, test_name)
if (test_type == TestType.PY):
binary_file = ('python ' + binary_file)
... |
def _masked_coo(A, mask):
row = A.row[mask]
col = A.col[mask]
data = A.data[mask]
return coo_matrix((data, (row, col)), shape=A.shape, dtype=A.dtype) |
class LimitDataTransformer(BaseEstimator, TransformerMixin):
def __init__(self, num_imp):
self.num_imp = num_imp
def fit(self, X, *args):
return self
def transform(self, df):
df = df[(df['impression'] > self.num_imp)]
return df |
.usefixtures('spark', 'columns')
()
def simple_dataframe(spark, columns):
data = [(1, 2, 19842), (1, 4, 19844), (1, 3, 19843), (1, 5, 19845), (1, 6, 19846), (1, 7, 19847), (2, 1, 19841), (2, 2, 19842), (2, 3, 19843), (2, 4, 19844), (3, 10, 19844), (4, 11, 19843), (4, 12, 19845), (1, 1, 19841)]
return spark.crea... |
def filter_depcc_svo(depcc_svo_fpath, output_fpath, common_svo):
with gzip.open(depcc_svo_fpath, 'rt', encoding='utf-8') as dep_in, gzip.open(output_fpath, 'wt', encoding='utf-8') as dep_out:
svo_num = 0
common_svo_num = 0
for (i, line) in enumerate(dep_in):
try:
... |
def _serialize_swagger2(definitions: DefinitionList) -> Generator[((Callable | None), None, None)]:
for definition in definitions:
name = definition['name']
collection_format = definition.get('collectionFormat', 'csv')
type_ = definition.get('type')
if (definition['in'] == 'header'):... |
class MagmaGBLogPrettyPrinter():
cmd_inpt = re.compile('^>>>$')
app_inpt = re.compile('^Append\\(~_sage_, 0\\);$')
deg_curr = re.compile('^Basis length\\: (\\d+), queue length\\: (\\d+), step degree\\: (\\d+), num pairs\\: (\\d+)$')
pol_curr = re.compile('^Number of pair polynomials\\: (\\d+), at (\\d+)... |
(scope='module', params=(scipy.io._mmio, fmm), autouse=True)
def implementations(request):
global mminfo
global mmread
global mmwrite
mminfo = request.param.mminfo
mmread = request.param.mmread
mmwrite = request.param.mmwrite |
def test_contingency_table():
im_true = np.array([1, 2, 3, 4])
im_test = np.array([1, 1, 8, 8])
table1 = np.array([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.25], [0... |
class AbsFrameModel(nn.Module):
def input_size(self) -> int:
raise NotImplementedError
def output_size(self) -> int:
raise NotImplementedError
def forward(self, x: torch.FloatTensor, x_len: torch.LongTensor) -> Tuple[(torch.FloatTensor, torch.LongTensor)]:
raise NotImplementedError |
class SlipperyJointsHopper(RoboschoolXMLModifierMixin, ModifiableRoboschoolHopper):
def __init__(self):
self.friction = 0.2
with self.modify_xml('hopper.xml') as tree:
for elem in tree.iterfind('default/geom'):
elem.set('friction', (str(self.friction) + ' .1 .1'))
... |
class CmodReLU(Module):
__constants__ = ['inplace']
inplace: bool
def __init__(self, threshold: int=None, inplace: bool=False):
super(CmodReLU, self).__init__()
self.inplace = inplace
if (not isinstance(threshold, float)):
threshold = Parameter((torch.rand(1) * 0.25))
... |
def calculate_metric(data, opt):
opt = deepcopy(opt)
metric_type = opt.pop('type')
metric = METRIC_REGISTRY.get(metric_type)(**data, **opt)
return metric |
def print_results(df, min_threshold):
precision = (sum(df['true_positive']) / (sum(df['true_positive']) + sum(df['false_positive'])))
recall = (sum(df['true_positive']) / (sum(df['true_positive']) + sum(df['false_negative'])))
f1_score = (((2 * precision) * recall) / (precision + recall))
speaker_match ... |
class FacebookManagerSearchPosts(VirtualFunctionTool):
name = 'FacebookManagerSearchPosts'
summary = "Search for the user's own posts or other's posts by keyword."
parameters: List[ArgParameter] = [{'name': 'user_id', 'type': 'string', 'description': 'The unique identifier of the user whose posts to search ... |
class ModulatedDeformRoIPoolingPack(DeformRoIPooling):
def __init__(self, spatial_scale, out_size, out_channels, no_trans, group_size=1, part_size=None, sample_per_part=4, trans_std=0.0, num_offset_fcs=3, num_mask_fcs=2, deform_fc_channels=1024):
super(ModulatedDeformRoIPoolingPack, self).__init__(spatial_s... |
.parametrize('ctx, func_name', ctxs)
.parametrize('seed', [313])
def test_asin_forward_backward(seed, ctx, func_name):
from nbla_test_utils import function_tester
rng = np.random.RandomState(seed)
inputs = [np.clip(rng.randn(2, 3, 4).astype(np.float32), (- 0.9), 0.9)]
function_tester(rng, F.asin, np.arc... |
def number2onehot(number):
onehot = [0 for i in range(12)]
for i in number:
onehot[i] = 1
return onehot |
def make_arch_string(ordered_arg_names=[], args_to_ignore=[], **kwargs):
starting_args = [str(kwargs.pop(arg_key)) for arg_key in ordered_arg_names]
for arg_key in args_to_ignore:
kwargs.pop(arg_key, None)
remaining_tuples = kwargs.items()
sorted_remaining_tuples = list(sorted(remaining_tuples))... |
def print_scores(scores, etype):
turns = ['turn 1', 'turn 2', 'turn 3', 'turn 4', 'turn >4']
levels = ['easy', 'medium', 'hard', 'extra', 'all', 'joint_all']
partial_types = ['select', 'select(no AGG)', 'where', 'where(no OP)', 'group(no Having)', 'group', 'order', 'and/or', 'IUEN', 'keywords']
print('{... |
class HashUnpinned(HashError):
order = 3
head = 'In --require-hashes mode, all requirements must have their versions pinned with ==. These do not:' |
class TestHparamsRegistry(unittest.TestCase):
(itertools.product(algorithms.ALGORITHMS, datasets.DATASETS))
def test_random_hparams_deterministic(self, algorithm_name, dataset_name):
a = hparams_registry.random_hparams(algorithm_name, dataset_name, 0)
b = hparams_registry.random_hparams(algorith... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.