code stringlengths 101 5.91M |
|---|
def make_prediction_list(datasets: dict[(DevTest, list[RawData])], predictions: dict[(DevTest, dict[(str, dict)])]) -> tuple[(dict[(DevTest, list[int])], dict[(DevTest, list[float])])]:
scores_dict_of_list: dict[(DevTest, list[float])] = {}
labels_dict_of_list: dict[(DevTest, list[int])] = {}
for split in [... |
def read_data(prefix, labels_dic, mixing, files_from_cl):
image_list = sorted(map((lambda x: os.path.join(prefix, x)), filter((lambda x: x.endswith('JPEG')), files_from_cl)))
prefix2 = np.array([file_i.split((prefix + '/'))[1].split('_')[0] for file_i in image_list])
labels_list = np.array([mixing[labels_di... |
def test_init_negative_approach_level():
with pytest.raises(AssertionError):
ControlFlowDistance(approach_level=(- 1)) |
def main():
try:
(opts, args) = getopt.getopt(sys.argv[1:], '')
except:
usage(sys.argv[0])
for (opt, arg) in opts:
usage(sys.argv[0])
if (len(args) != 3):
usage(sys.argv[0])
num_pairs = int(args[0])
N = int(args[1])
Np = int(args[2])
if (Np > N):
s... |
class AcquisitionFunctionBuilder(Generic[ProbabilisticModelType], ABC):
def prepare_acquisition_function(self, models: Mapping[(Tag, ProbabilisticModelType)], datasets: Optional[Mapping[(Tag, Dataset)]]=None) -> AcquisitionFunction:
def update_acquisition_function(self, function: AcquisitionFunction, models: Ma... |
class TestSensitivityMetricInterestPoints(unittest.TestCase):
def test_filtered_interest_points_set(self):
in_model = DenseNet121()
(ips, graph, fw_info) = build_ip_list_for_test(in_model, num_interest_points_factor=0.5)
sorted_nodes = graph.get_topo_sorted_nodes()
ip_nodes = list(fi... |
.parametrize('vec', [[1, 1], [1, 0.01], [0.01, 1], [0, 0, 0]])
def test_axisvec2axis_no_primary_coordinate_raises_value_error(vec):
with pytest.raises(ValueError, match='no valid primary coordinate axis'):
axisvec2axis(vec) |
def register_Ns3EventId_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('==')
cls.add_constructor([param('ns3::EventId const &', 'arg0')])
cls.add_constructor([])
cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('u... |
def train(category):
print(('counter = %d, train for category %s' % (counter, category)))
print(cameraURL)
for i in range(10):
response = requests.get(cameraURL)
img = Image.open(BytesIO(response.content))
emb = engine.DetectWithImage(img)
engine.addEmbedding(emb, category) |
class Module(object):
def __init__(self, name, members):
self.name = name
self.members = members
def __getattr__(self, name):
try:
return self.members[name]
except KeyError:
raise RuntimeError(f'Module {self.name} has no member called {name}') from None |
def batch_iter(X, batch_size=args.batch_size, shuffle=False):
if shuffle:
idxs = torch.randperm(X.shape[0])
else:
idxs = torch.arange(X.shape[0])
if X.is_cuda:
idxs = idxs.cuda()
for batch_idxs in idxs.split(batch_size):
(yield X[batch_idxs]) |
def load_data(path, test_strat_id=None, cuda=None):
data = joblib.load(path)
type_remap = (- np.ones((int(data['features']['atom_types'].max()) + 1)))
unique_types = np.unique(data['features']['atom_types']).astype(int)
type_remap[unique_types] = np.arange(len(unique_types))
data['features']['atom_t... |
def build_hoi_test_loader(cfg, dataset_name, mapper=None):
dataset_dicts = get_hoi_dataset_dicts([dataset_name], filter_empty=False)
dataset = DatasetFromList(dataset_dicts)
if (mapper is None):
mapper = HOIDatasetMapper(cfg, False)
dataset = MapDataset(dataset, mapper)
sampler = samplers.In... |
def flatten_model(m):
return (sum(map(flatten_model, m.children()), []) if len(list(m.children())) else [m]) |
class DifferentiableArray(ak.Array):
def __init__(self, aux_data, tracers):
self.aux_data = aux_data
self.tracers = tracers
def layout(self):
buffers = dict(self.aux_data.indexes)
for (key, tracer) in zip(self.aux_data.datakeys, self.tracers):
if hasattr(tracer, 'prim... |
def draw_keypoints(img, corners, color, radius=3, s=3):
img = np.repeat(cv2.resize(img, None, fx=s, fy=s)[(..., np.newaxis)], 3, (- 1))
for c in np.stack(corners).T:
cv2.circle(img, tuple((s * np.flip(c, 0))), radius, color, thickness=(- 1))
return img |
def test_categorical_option():
pytest.importorskip('pyarrow')
array = ak.str.to_categorical(['do', 're', 'mi', 'fa', 'so', None])
form_from_type = ak.forms.from_type(array.type.content)
assert (form_from_type == array.layout.form) |
def get_vocab(dataset, vocab_size):
if (vocab_size == 'null'):
return None
return pickle.load(open(f'data/{dataset}/vocab_{vocab_size}.pickle', 'rb')) |
def prepare_tag(split, src, datadir, eval=False, max_len=512, stride=300, data=None, suffix='', offset=0, jsonl=True):
def _check_is_max_context(doc_spans, cur_span_index, position):
best_score = None
best_span_index = None
for (span_index, doc_span) in enumerate(doc_spans):
end ... |
_toolkit()
class GitHub(FunctionToolkit):
name_for_human = 'GitHub'
description_for_human = 'Toolkit for managing GitHub repositories and user details.'
name_for_model = 'GitHub'
description_for_model = 'A toolkit for managing GitHub repositories, including searching for repositories, retrieving reposit... |
class ColorJitter(object):
def __init__(self, brightness=0.5, contrast=0.5, saturation=0.5):
if ((not (brightness is None)) and (brightness > 0)):
self.brightness = [max((1 - brightness), 0), (1 + brightness)]
if ((not (contrast is None)) and (contrast > 0)):
self.contrast = ... |
class DataPreprocessor():
def __init__(self, data_augmenter_spec: DataAugmenterSpec):
self.data_augmenter_spec: DataAugmenterSpec = data_augmenter_spec
(None)
def preprocess(self, instances: List[Instance], parallelism: int=1) -> List[Instance]:
data_augmenter: DataAugmenter = create_data_au... |
def custom_augment(image):
image = image['image']
image = tf.image.convert_image_dtype(image, tf.float32)
image = tf.image.resize(image, (224, 224))
image = random_apply(tf.image.flip_left_right, image, p=0.5)
image = random_apply(translate, image, p=0.5)
image = random_apply(gaussian_blur, imag... |
def register_Ns3ThreeGppHttpHeader_methods(root_module, cls):
cls.add_constructor([param('ns3::ThreeGppHttpHeader const &', 'arg0')])
cls.add_constructor([])
cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True)
cls.add_method('GetClientTs', 'ns3::Time', [... |
class NoRepeatNGramLogitsProcessor():
def __init__(self, *args, **kwargs):
requires_pytorch(self) |
_utils.test(exclude=[ti.amdgpu])
def test_arg_4k():
vec1024 = ti.types.vector(1024, ti.i32)
def bar(a: vec1024) -> ti.i32:
ret = 0
for i in range(1024):
ret += a[i]
return ret
a = vec1024([i for i in range(1024)])
assert (bar(a) == 523776) |
def show():
for (name, info_dict) in globals().items():
if ((name[0] == '_') or (type(info_dict) is not type({}))):
continue
print((name + ':'))
if (not info_dict):
print(' NOT AVAILABLE')
for (k, v) in info_dict.items():
v = str(v)
if... |
def SetAdd(s, e):
ctx = _ctx_from_ast_arg_list([s, e])
e = _py2expr(e, ctx)
return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx) |
def get_cached_models(cache_dir: Union[(str, Path)]=None) -> List[Tuple]:
if (cache_dir is None):
cache_dir = TRANSFORMERS_CACHE
elif isinstance(cache_dir, Path):
cache_dir = str(cache_dir)
if (not os.path.isdir(cache_dir)):
return []
cached_models = []
for file in os.listdir... |
def general_stats_data_public(path):
df = pd.read_json(path)
query_type_label = {'LOCATION': 0, 'DESCRIPTION': 0, 'NUMERIC': 0, 'ENTITY': 0, 'PERSON': 0}
total_size = len(df)
for row in df.iterrows():
category = row[1]['query_type']
if (category in query_type_label):
query_ty... |
def _get_initial_states(self, client_id, observation, policy: Policy, identifier):
if ((client_id is not None) and (len(self.clients[client_id].rnn_states[identifier]) > 0)):
return self.clients[client_id].rnn_states[identifier][(- 1)]
else:
offset = len(policy.preprocessor.shape)
if (of... |
def cleaning(x):
x = re.sub(re.compile('<.*?>'), '', x)
x = re.compile('<\\s*style[^>]*>.*?<\\s*/\\s*style\\s*>', (re.S | re.I)).sub('', x)
x = re.compile('<\\s*script[^>]*>.*?<\\s*/\\s*script\\s*>', (re.S | re.I)).sub('', x)
x = clean(x, fix_unicode=True, to_ascii=False, lower=True, no_line_breaks=True... |
def save_secondary_output(model, out_file, ranked_results, secondary_output, max_sec_i):
filtered_secondary_output = {}
for (q_id, ranked_doc_ids) in ranked_results.items():
filtered_secondary_output[q_id] = {}
for (i, doc_id) in enumerate(ranked_doc_ids):
if (i == max_sec_i):
... |
def get_rng_state_all():
results = []
for i in range(device_count()):
with device_ctx_manager(i):
results.append(get_rng_state())
return results |
def get_loss(factorexprs, gold_fes, valid_fes, sentlen):
if (options.loss == 'hinge'):
return get_hinge_loss(factorexprs, gold_fes, valid_fes, sentlen)
goldfactors = [Factor(span[0], span[1], feid) for feid in gold_fes for span in gold_fes[feid]]
numeratorexprs = [factorexprs[gf] for gf in goldfacto... |
class MiT(nn.Module):
def __init__(self, model_name: str='B0'):
super().__init__()
assert (model_name in mit_settings.keys()), f'MiT model name should be in {list(mit_settings.keys())}'
(embed_dims, depths) = mit_settings[model_name]
drop_path_rate = 0.1
self.channels = embed... |
class set_scriptable():
def __init__(self, mode: bool) -> None:
global _SCRIPTABLE
self.prev = _SCRIPTABLE
_SCRIPTABLE = mode
def __enter__(self) -> None:
pass
def __exit__(self, *args: Any) -> bool:
global _SCRIPTABLE
_SCRIPTABLE = self.prev
return Fa... |
def validate_jp_cn(df: Union[(str, pd.Series, dd.Series, pd.DataFrame, dd.DataFrame)], column: str='') -> Union[(bool, pd.Series, pd.DataFrame)]:
if isinstance(df, (pd.Series, dd.Series)):
return df.apply(cn.is_valid)
elif isinstance(df, (pd.DataFrame, dd.DataFrame)):
if (column != ''):
... |
def projected_memory_usage(node: V1Node, pod: Optional[V1Pod], usage: Dict[(str, Union[(int, float)])]) -> Union[(int, float)]:
try:
usage = usage[node.metadata.name]
except KeyError:
usage = 0
if (pod is not None):
usage += pod_sum_resources_requests(pod, ('intel.com/sgx' if pod_req... |
class SympyOverridesTest(TestCase):
def test_solve(self) -> None:
(x, y) = sf.symbols('x y')
solution = sf.solve(((x - 2) * (x + y)), x)
self.assertIsInstance(solution, T.List)
self.assertEqual(set(solution), {2, (- y)})
solution = sf.solve(2, x)
self.assertIsInstance... |
def substruct2smi(molecule, partitioning, cg_bead, cgbeads, ringatoms):
frag = rdchem.EditableMol(molecule)
num_atoms = molecule.GetConformer().GetNumAtoms()
for i in range(num_atoms):
if (molecule.GetAtomWithIdx(i).GetSymbol() == 'H'):
submol = frag.GetMol()
for j in range(s... |
class LayerDecayValueAssigner(object):
def __init__(self, values, is_swin=False, depths=None):
self.values = values
self.is_swin = is_swin
self.depths = depths
def get_scale(self, layer_id):
return self.values[layer_id]
def get_layer_id(self, var_name):
return (get_nu... |
def sharp_ifeq(lvalue, rvalue, valueIfTrue, valueIfFalse=None, *args):
rvalue = rvalue.strip()
if rvalue:
if (lvalue.strip() == rvalue):
if valueIfTrue:
return valueIfTrue.strip()
elif valueIfFalse:
return valueIfFalse.strip()
return '' |
class CircleMaze():
def __init__(self):
self.ring_r = 0.15
self.stop_t = 0.05
self.s_angle = 30
self.mean_s0 = (float(np.cos(((np.pi * self.s_angle) / 180))), float(np.sin(((np.pi * self.s_angle) / 180))))
self.mean_g = (float(np.cos(((np.pi * (360 - self.s_angle)) / 180))), ... |
class AverageMeter(object):
def __init__(self, name=None, fmt='.6f'):
fmtstr = f'{{val:{fmt}}} ({{avg:{fmt}}})'
if (name is not None):
fmtstr = ((name + ' ') + fmtstr)
self.fmtstr = fmtstr
self.reset()
def reset(self):
self.val = 0
self.sum = 0
... |
def sliding_windows(item=None, rank_start=0, rank_end=100, window_size=20, step=10, model_name='gpt-3.5-turbo', api_key=None):
item = copy.deepcopy(item)
end_pos = rank_end
start_pos = (rank_end - window_size)
while (start_pos >= rank_start):
start_pos = max(start_pos, rank_start)
item =... |
def find_missing_pose_files(directory: str):
all_files = os.listdir(directory)
mp4_files = [f for f in all_files if f.endswith('.mp4')]
pose_files = {f.removesuffix('.pose') for f in all_files if f.endswith('.pose')}
missing_pose_files = []
for mp4_file in mp4_files:
base_name = mp4_file.rem... |
def count_single_mulpies(toks, ratio=RATIO):
if isinstance(toks, str):
toks = toks.split()
mulpies = dict()
chord_dict = Counter()
l_toks = len(toks)
for idx in range(0, l_toks, ratio):
(e, d) = toks[idx:(idx + 2)]
if (not ispitch(e)):
if (len(mulpies) > 0):
... |
def _distance_to_closest_point(point, points):
return min((distance_between_points(point, p) for p in points)) |
def squad_convert_examples_to_features(examples, tokenizer, max_seq_length, doc_stride, max_query_length, is_training, return_dataset=False, threads=1):
features = []
threads = min(threads, cpu_count())
with Pool(threads, initializer=squad_convert_example_to_features_init, initargs=(tokenizer,)) as p:
... |
class AdamClonedWeightPredictionForAggregationWithWD(WeightPredictor):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
adam_init(self.optimizer)
def forward(self):
if (not self.n_steps):
return
self.true_weights_storage.create_cloned_if_needed()
... |
class PDFParser_1911_08265(PDFParser):
def _format_df(self):
tables = camelot.read_pdf('../pdfs/1911.08265.pdf', pages='17,18', flavor='stream')
df_noop = tables[0].df
df_noop = df_noop.iloc[:(- 1)].drop(columns=[7])
df_noop = df_noop.T
df_noop = self._remove_index_and_header... |
_module()
class ResNeXt(ResNet):
arch_settings = {50: (Bottleneck, (3, 4, 6, 3)), 101: (Bottleneck, (3, 4, 23, 3)), 152: (Bottleneck, (3, 8, 36, 3))}
def __init__(self, groups=1, base_width=4, **kwargs):
self.groups = groups
self.base_width = base_width
super(ResNeXt, self).__init__(**kw... |
('matplotlib', '>=3.3')
def try_all_threshold(image, figsize=(8, 5), verbose=True):
def thresh(func):
def wrapper(im):
return (im > func(im))
try:
wrapper.__orifunc__ = func.__orifunc__
except AttributeError:
wrapper.__orifunc__ = ((func.__module__ + '.') ... |
def renameDatasetColumn(dataset):
col_names = dataset.column_names
for cols in col_names:
if ('-' in cols):
dataset = dataset.rename_column(cols, cols.replace('-', '_'))
return dataset |
class TestShapTabular(unittest.TestCase):
def test_explain(self):
task = TabularRegression().train_boston()
predict_function = (lambda z: task.model.predict(task.transform.transform(z)))
set_random_seed()
explainer = ShapTabular(training_data=task.train_data, predict_function=predict... |
def is_gcov_enabled(cargs):
if (not is_exe(cargs.readelf_path)):
print('[*] Need a valid path to readelf, use --readelf-path')
return False
if cargs.coverage_cmd:
if ('AFL_FILE' not in cargs.coverage_cmd):
print('[*] --coverage-cmd must contain AFL_FILE')
return F... |
class EFDTActiveLeaf(ActiveLeafClass):
def get_null_split(self, criterion):
pre_split_dist = self.stats
null_split = AttributeSplitSuggestion(None, [{}], criterion.get_merit_of_split(pre_split_dist, [pre_split_dist]))
if (null_split.merit == (- np.inf)):
null_split.merit = 0.0
... |
def conv_init(m):
classname = m.__class__.__name__
if (classname.find('Conv') != (- 1)):
init.xavier_uniform_(m.weight, gain=np.sqrt(2))
init.constant_(m.bias, 0)
elif (classname.find('BatchNorm') != (- 1)):
init.constant_(m.weight, 1)
init.constant_(m.bias, 0) |
def expected_calibration_error(confs, preds, labels, num_bins=10):
def _populate_bins(confs, preds, labels, num_bins):
bin_dict = defaultdict((lambda : {'bin_accuracy': 0, 'bin_confidence': 0, 'count': 0}))
bins = np.linspace(0, 1, (num_bins + 1))
for (conf, pred, label) in zip(confs, preds,... |
class DenseController(Controller):
def __init__(self, incoming, memory_shape, num_units, num_reads, W_in_to_hid=lasagne.init.GlorotUniform(), b_in_to_hid=lasagne.init.Constant(0.0), W_reads_to_hid=lasagne.init.GlorotUniform(), b_reads_to_hid=lasagne.init.Constant(0.0), nonlinearity=lasagne.nonlinearities.rectify, h... |
class Exponential(Benchmark):
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip(([(- 1.0)] * self.N), ([1.0] * self.N)))
self.global_optimum = [[0.0 for _ in range(self.N)]]
self.fglob = (- 1.0)
self.change_dimensionality = True
... |
def estimate_hoeffding_lower_bound(x: np.ndarray, x_max: Optional[float]=None, delta: float=0.05) -> float:
if (x_max is None):
x_max = x.max()
else:
check_scalar(x_max, 'x_max', (int, float), min_val=x.max())
check_scalar(delta, 'delta', (int, float), min_val=0.0, max_val=1.0)
n = x.sha... |
class DownsampleA(nn.Module):
def __init__(self, nIn, nOut, stride):
super(DownsampleA, self).__init__()
assert (stride == 2)
self.avg = nn.AvgPool2d(kernel_size=1, stride=stride)
def forward(self, x):
x = self.avg(x)
return torch.cat((x, x.mul(0)), 1) |
class DeepConfig(Config):
def __init__(self, batch_size: int=32, num_epochs: int=10, optimizer: Union[(str, Optimizer)]=Optimizer.Adam, loss_fn: Union[(str, LossFunction)]=LossFunction.mse, clip_gradient: Optional[float]=None, use_gpu: bool=True, ts_encoding: Union[(None, str)]='h', lr: float=0.0001, weight_decay: ... |
def braid_in_segment(glist, x0, x1, precision={}):
precision1 = {_: precision[_] for _ in precision.keys()}
g = prod(glist)
F1 = g.base_ring()
(x, y) = g.parent().gens()
X0 = F1(x0)
X1 = F1(x1)
intervals = {}
if (not precision1):
precision1 = {f: 53 for f in glist}
y0s = []
... |
class ResGRU(ResRNNBase):
def __init__(self, ninp, nhid, nlayers, dropout, direction):
super(ResGRU, self).__init__('GRU', ninp, nhid, nlayers, dropout=dropout, direction=direction) |
def args2powersetdict(args: Any, powerset_args: List[Any], args_unique: List[Any], dict_args_cfg_empty: Dict[(str, Any)]) -> Tuple[(Any, Any)]:
dicts_sets = []
names_sets = []
powerset = [getattr(args, arg) for arg in powerset_args]
combinations = list(itertools.product(*powerset))
for pset in combi... |
def mp_hyp2f1(a, b, c, z):
on_branch_cut = ((z.real > 1.0) and (abs(z.imag) < 1e-15))
cond1 = ((abs(((c - a) - round((c - a)))) < 1e-15) and (round((c - a)) <= 0))
cond2 = ((abs(((c - b) - round((c - b)))) < 1e-15) and (round((c - b)) <= 0))
if on_branch_cut:
z = (z.real + 0j)
if (on_branch_... |
def test__rollback_changes_nothing_to_rollback(default_test_case):
default_test_case.add_statement(stmt.IntPrimitiveStatement(default_test_case, 5))
default_test_case.add_statement(stmt.IntPrimitiveStatement(default_test_case, 10))
default_test_case.add_statement(stmt.IntPrimitiveStatement(default_test_case... |
def get_optimizer(args, net):
base_params = []
for (name, param) in net.named_parameters():
base_params.append(param)
if args.sgd:
optimizer = optim.SGD(base_params, lr=args.lr, weight_decay=0.0005, momentum=args.momentum, nesterov=False)
else:
raise ValueError('Not a valid optim... |
class Embedder(metaclass=abc.ABCMeta):
def tokenize(self, sentence):
pass
def untokenize(self, tokens):
pass
def lookup(self, token):
pass
def contains(self, token):
pass
def to(self, device):
pass |
_function_from_c_func_and_dispatcher(_multiarray_umath.copyto)
def copyto(dst, src, casting=None, where=None):
return (dst, src, where) |
.parametrize('attr', simulation_state_nparray_attrs)
def test_hdf_simulation_state_nparray(hdf_file_path, simulation_verysimple, attr):
path = f'simulation_state/{attr}'
expected = pd.read_hdf(hdf_file_path, path)
actual = getattr(simulation_verysimple.simulation_state, attr)
if hasattr(actual, 'cgs'):
... |
def get_variants_sparse(domain, task, policy, seed, gamma):
RUN_PARAMS_BASE['seed'] = seed
ALGORITHM_PARAMS_BASE['discount'] = gamma
params = {'prefix': '{}/{}'.format(domain, task), 'domain': domain, 'task': task, 'git_sha': get_git_rev(), 'env_params': ENV_PARAMS[domain].get(task, {}), 'policy_params': PO... |
class IPERProtocol(Protocol):
def __init__(self, data_dir='/p300/iPER'):
super().__init__()
self.data_dir = data_dir
self.train_ids_file = 'train.txt'
self.test_ids_file = 'val.txt'
self.eval_path = 'iPER_protocol.json'
self.images_folder = 'images_HD'
self.sm... |
def typeset_solvers_table(fd, solver_table):
rest_tag_start = '.. <%s>\n'
rest_tag_end = '.. </%s>\n'
for solver_type in solver_table:
fd.write((rest_tag_start % solver_type[1]))
for (name, cls) in sorted(solver_type[0].items()):
fd.write(('- :class:`%s <%s.%s>`: ' % (name, cls._... |
class EMA(object):
def __init__(self, mu=0.999):
self.mu = mu
self.shadow = {}
def register(self, module):
for (name, param) in module.named_parameters():
if param.requires_grad:
self.shadow[name] = param.data.clone()
def update(self, module):
for ... |
class TFMT5Model(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
class TestWeightSetting(unittest.TestCase):
def test_obtain_weights(self):
power_signals_d = np.array([[0., 0.0, 0.0, 2.], [0., 0.0, 0.0, 2.], [0.8125, 0.0, 0.0, 2.], [0., 0.0, 0.0, 2.]])
expected_weights = np.array([0.0, 0.0, 0.0, 0.0])
weight_setting = WeightSetting()
actual_weight... |
def load_fasttext(language):
lang = constants.LANGUAGE_CODES[language]
ft_path = 'data/fasttext'
ft_fname = os.path.join(ft_path, ('cc.%s.300.bin' % lang))
if (not os.path.exists(ft_fname)):
logging.info('Downloading fasttext model')
temp_fname = fasttext.util.download_model(lang, if_exi... |
def register_Ns3Dot11sIePeeringProtocol_methods(root_module, cls):
cls.add_constructor([param('ns3::dot11s::IePeeringProtocol const &', 'arg0')])
cls.add_constructor([])
cls.add_method('DeserializeInformationField', 'uint8_t', [param('ns3::Buffer::Iterator', 'i'), param('uint8_t', 'length')], is_virtual=Tru... |
class stacked_DMSHN(nn.Module):
def __init__(self):
super(stacked_DMSHN, self).__init__()
self.net1 = DMSHN()
self.net2 = DMSHN()
def forward(self, x):
out1 = self.net1(x)
out2 = self.net2(out1)
return out2 |
def worker(remote, parent_remote, env_fn_wrapper):
parent_remote.close()
env = env_fn_wrapper.x()
while True:
(cmd, data) = remote.recv()
if (cmd == 'step'):
(ob, reward, done, info) = env.step(data)
if done:
ob = env.reset()
remote.send((o... |
def linear_layer(x, is_training, num_classes, use_bias=True, use_bn=False, name='linear_layer'):
assert (x.shape.ndims == 2), x.shape
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
x = tf.layers.dense(inputs=x, units=num_classes, use_bias=(use_bias and (not use_bn)), kernel_initializer=tf.random_nor... |
class BaseTracker():
def __init__(self, cutie_checkpoint, device) -> None:
config = OmegaConf.create(CONFIG)
network = CUTIE(config).to(device).eval()
model_weights = torch.load(cutie_checkpoint, map_location=device)
network.load_weights(model_weights)
self.tracker = Inferenc... |
class ElementWiseArrayOperation(pm.SingleStateTransformation):
map_entry = pm.PatternNode(nodes.MapEntry)
def expressions(cls):
return [sdutil.node_path_graph(cls.map_entry)]
def can_be_applied(self, graph: dace.SDFGState, expr_index: int, sdfg: dace.SDFG, permissive: bool=False):
map_entry ... |
def validate_callable(property_name, obj):
if (not callable(obj)):
raise TypeError(f'{property_name} must be callable and {type(obj)} is not.')
return obj |
class Issue4RunEquality(unittest.TestCase):
def setUp(self):
self._path = os.path.dirname(os.path.realpath(__file__))
def _create_template_run_id():
executor = Executor('MyVM', 'foo_bar_path', 'foo_bar_bin', None, None, None, None, None, None, 'benchmark', {})
suite = BenchmarkSuite('MyS... |
def matching_by_voting(src_token_list, tgt_token_list, tgt_attr_list):
assert (len(src_token_list) <= len(tgt_token_list))
assert (len(tgt_token_list) == len(tgt_attr_list))
src_attr_list = []
idx_tgt = 0
for src_token in src_token_list:
attr_buff = []
idx_char = 0
while (idx... |
def _arg_val(arg):
if arg.HasField('f'):
return str(arg.f)
if arg.HasField('i'):
return str(arg.i)
if arg.HasField('s'):
return _sanitize_str(arg.s)
if arg.floats:
return str(list(arg.floats))
if arg.ints:
return str(list(arg.ints))
if arg.strings:
... |
class VAEEncoder(nn.Module):
_encoder: EncoderWithAction
_mu: nn.Module
_logstd: nn.Module
_min_logstd: float
_max_logstd: float
_latent_size: int
def __init__(self, encoder: EncoderWithAction, hidden_size: int, latent_size: int, min_logstd: float=(- 20.0), max_logstd: float=2.0):
su... |
def decode(z):
sents = []
i = 0
while (i < len(z)):
zi = torch.tensor(z[i:(i + args.batch_size)], device=device)
outputs = model.generate(zi, args.max_len, args.dec).t()
for s in outputs:
sents.append([vocab.idx2word[id] for id in s[1:]])
i += args.batch_size
... |
class ModelArguments():
model_name_or_path: str = field(metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'})
config_name: Optional[str] = field(default=None, metadata={'help': 'Pretrained config name or path if not the same as model_name'})
tokenizer_name: Optional[s... |
class ThinkAgent():
def __init__(self, llm, context_len=2000):
self.type = 'Think_Webrun_Agent'
self.name = f'{self.type}_{self.life_label}'
self.llm = llm
self.context_len = context_len
self.task = None
def action_parser(self, text):
nor_text = text.strip().lower... |
.experimental
def test_works(log, model):
try:
pred = model.fit_predict(log, k=1)
assert (pred.count() == 4)
except:
pytest.fail() |
class LinearWarmupScheduler(BaseLearningRateScheduler):
def __init__(self, scheduler, warmup_iter):
self.scheduler = scheduler
self.warmup_iter = warmup_iter
def get_learning_rate(self, iter):
lr = self.scheduler.get_learning_rate(iter)
if (iter < self.warmup_iter):
l... |
def _set_SIGCHLD_handler():
if (sys.platform == 'win32'):
return
if (not isinstance(threading.current_thread(), threading._MainThread)):
return
global _SIGCHLD_handler_set
if _SIGCHLD_handler_set:
return
previous_handler = signal.getsignal(signal.SIGCHLD)
if (not callable... |
def parse_args(argv):
parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False)
group = parser.add_argument_group('General Options')
opts.add_general_flags(group)
group = parser.add_argument_group('Dataset Options')
opts.add_dataset_flags(group)
group = parser.add_argument_group(... |
def _get_logger(name=None, level='INFO'):
level = _get_level(level)
if (name is None):
name = ROOT_NAME
assert isinstance(name, str)
if (not name.startswith(ROOT_NAME)):
name = '{}.{}'.format(ROOT_NAME, name)
logger = logging.getLogger(name)
logger.setLevel(level)
return logg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.