code stringlengths 101 5.91M |
|---|
class RandomTranslate(object):
def __init__(self, offset):
self.offset = offset
def __call__(self, img, mask):
assert (img.size == mask.size)
x_offset = int(((2 * (random.random() - 0.5)) * self.offset[0]))
y_offset = int(((2 * (random.random() - 0.5)) * self.offset[1]))
... |
def format_submit(X, sub_id, submit_dir='../submissions/'):
header = ['user_id', 'items']
for (pos, key) in enumerate(X):
l = X[key]
if isinstance(l, list):
X[key] = ','.join((str(xx) for xx in l))
else:
break
x = pd.DataFrame(X.items())
write_csv(x, join(... |
def get_same_padding_conv2d(image_size=None):
if (image_size is None):
return Conv2dDynamicSamePadding
else:
return partial(Conv2dStaticSamePadding, image_size=image_size) |
class TFData2VecVisionModel(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
class PReLU_SENet(nn.Module):
def __init__(self, block, num_blocks, num_classes=100):
super(PReLU_SENet, self).__init__()
self.in_planes = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.layer1 = self._make_l... |
def _dora_array(state: State, riichi):
def next(tile):
return jax.lax.cond((tile < 27), (lambda : ((tile // 9) + ((tile + 1) % 9))), (lambda : jax.lax.cond((tile < 31), (lambda : (27 + ((tile + 1) % 4))), (lambda : (31 + ((tile + 1) % 3))))))
dora = jnp.zeros(34, dtype=jnp.bool_)
return jax.lax.cond... |
def rank_ZZ(n=700, min=0, max=9, system='sage'):
if (system == 'sage'):
A = random_matrix(ZZ, n, (n + 10), x=min, y=(max + 1))
t = cputime()
v = A.rank()
return cputime(t)
elif (system == 'magma'):
code = ('\nn := %s;\nA := RMatrixSpace(IntegerRing(), n, n+10)![Random(%s,... |
def VGG16(include_top=True, weights='imagenet', input_tensor=None):
if (weights not in {'imagenet', None}):
raise ValueError('The `weights` argument should be either `None` (random initialization) or `imagenet` (pre-training on ImageNet).')
if (K.image_dim_ordering() == 'th'):
if include_top:
... |
def generate_points_for_circle(centerx, centery, r, density_factor):
pts_on_circle = []
num_points = int((((2 * 3.141) * r) * density_factor))
angles = np.linspace(0, (2.0 * 3.141), num_points)
for angle in angles:
x = ((math.sin(angle) * r) + centerx)
y = ((math.cos(angle) * r) + center... |
class TransformerInitModel(nn.Module):
def __init__(self, config, output_attentions, *inputs, **kwargs):
super(TransformerInitModel, self).__init__()
self.config = config
self.output_attentions = output_attentions
def init_Transformer_weights(self, module):
if isinstance(module, ... |
_start_docstrings(CUSTOM_DPR_READER_DOCSTRING)
class CustomDPRReaderTokenizerMixin():
def __call__(self, questions, titles: Optional[str]=None, texts: Optional[str]=None, padding: Union[(bool, str)]=False, truncation: Union[(bool, str)]=False, max_length: Optional[int]=None, return_tensors: Optional[Union[(str, Ten... |
def module_init():
root_module = Module('ns.tap_bridge', cpp_namespace='::ns3')
return root_module |
def Gamma_constructor(N):
if (N == 1):
return SL2Z
try:
return _gamma_cache[N]
except KeyError:
_gamma_cache[N] = Gamma_class(N)
return _gamma_cache[N] |
_spec_function('viz_wiz')
def get_viz_wiz_spec() -> RunSpec:
scenario_spec = ScenarioSpec(class_name='helm.benchmark.scenarios.vision_language.viz_wiz_scenario.VizWizScenario', args={})
adapter_spec: AdapterSpec = get_vlm_generation_adapter_spec(input_prefix='User: ', input_suffix='<end_of_utterance>', output_p... |
class Score(nn.Module):
def __init__(self, embeds_dim, hidden_dim=150):
super().__init__()
self.score = nn.Sequential(nn.Linear(embeds_dim, hidden_dim), nn.ReLU(), nn.Dropout(0.2), nn.Linear(hidden_dim, hidden_dim), nn.ReLU(), nn.Dropout(0.2), nn.Linear(hidden_dim, 1))
def forward(self, x):
... |
class Stream_zero(Stream):
def __init__(self):
super().__init__(True)
self._approximate_order = infinity
def __getitem__(self, n):
return ZZ.zero()
def order(self):
return self._approximate_order
def __eq__(self, other):
return ((self is other) or isinstance(other... |
class TsStruct(StructBuilder, TsBase):
def __init__(self, package, struct, args):
super(TsStruct, self).__init__(package, struct, args)
self.members = [TsMember(member) for member in self.members]
self.constants = [TsMember(member) for member in self.constants]
def complex_members(self):... |
class FilteredModuleTestCluster(TestCluster):
def type_system(self) -> TypeSystem:
return self.__delegate.type_system
def update_return_type(self, accessible: GenericCallableAccessibleObject, new_type: ProperType) -> None:
self.__delegate.update_return_type(accessible, new_type)
def update_p... |
def test_countless2d():
def test_all_cases(fn, test_zero):
case1 = np.array([[1, 2], [3, 4]]).reshape((2, 2, 1, 1))
case2 = np.array([[1, 1], [2, 3]]).reshape((2, 2, 1, 1))
case1z = np.array([[0, 1], [2, 3]]).reshape((2, 2, 1, 1))
case2z = np.array([[0, 0], [2, 3]]).reshape((2, 2, 1,... |
def register_Ns3RngRsp_methods(root_module, cls):
cls.add_constructor([param('ns3::RngRsp const &', 'arg0')])
cls.add_constructor([])
cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True)
cls.add_method('GetAasBdcastPermission', 'uint8_t', [], is_const=Tru... |
def get_init_with_noise(model, X, y):
init = X.clone()
p = model(X).argmax(1)
while any((p == y)):
init = torch.where(atleast_kdim((p == y), len(X.shape)), (X + (0.5 * torch.randn_like(X))).clip(0, 1), init)
p = model(init).argmax(1)
return init |
def main(fn=None, *, args: Optional[List[str]]=None, config_dir: Optional[str]=DEFAULT_CONFIG_DIR):
if (fn is None):
return functools.partial(main, args=args, config_dir=config_dir)
_cmdline_args = args
if (args is None):
_cmdline_args = sys.argv[1:]
(fn)
def wrapper_inner(*args, **k... |
class ConstantConvReuseSubstitutionTest(BaseConstantConvSubstitutionTest):
def __init__(self, unit_test):
super().__init__(unit_test)
class ConvNet(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 16, kernel_size=(3, 3), bias=False)
... |
def main():
print(__doc__)
fn = os.path.join('..', 'cephes', 'expn.h')
K = 12
A = generate_A(K)
with open((fn + '.new'), 'w') as f:
f.write(WARNING)
f.write(f'''#define nA {len(A)}
''')
for (k, Ak) in enumerate(A):
.join([str(x.evalf(18)) for x in Ak.coeffs()])
... |
class FooInterpreter(PostOrderInterpreter):
def eval_mult(self, node, args):
return (args[0] * args[1])
def eval_plus(self, node, args):
return (args[0] + args[1]) |
class ListOffsetMeta(Meta, Generic[T]):
is_list = True
_content: T
def purelist_parameters(self, *keys: str) -> JSONSerializable:
if (self._parameters is not None):
for key in keys:
if (key in self._parameters):
return self._parameters[key]
ret... |
class VideoGroundingDataset(Dataset):
EXCLUDE_FILES = {'activitynet': {'train': [], 'val': ['v_0dkIbKXXFzI', 'v_j73Wh1olDsA']}, 'charades': {'train': [], 'val': []}}
def __init__(self, root, dataset='activitynet', data_type='features', backbone='clip', phase='train', num_input_frames=32, num_input_sentences=16,... |
def evaluate_design(input_list, testbench, ground_truth, output, filename, path, liberty):
truth_dir = os.path.join(output, 'truthtable', (filename + '.truth'))
subprocess.call(([path['iverilog'], '-o', (truth_dir[:(- 5)] + 'iv'), testbench] + input_list))
with open(truth_dir, 'w') as f:
subprocess.... |
.parametrize('estimator, build_dataset', metric_learners, ids=ids_metric_learners)
def test_get_metric_raises_error(estimator, build_dataset):
(input_data, labels, _, X) = build_dataset()
model = clone(estimator)
set_random_state(model)
model.fit(*remove_y(model, input_data, labels))
metric = model.... |
.datainstrument
def test_symbol_dump_conditional():
def dinstr(A: dace.float64[20]):
for i in range(19):
A[(i + 1)] = (A[i] + 1)
sdfg = dinstr.to_sdfg(simplify=True)
for state in sdfg.states():
state.symbol_instrument = dace.DataInstrumentationType.Save
state.symbol_instr... |
def test_calinski_harabasz_score():
assert_raises_on_only_one_label(calinski_harabasz_score)
assert_raises_on_all_points_same_cluster(calinski_harabasz_score)
assert (1.0 == calinski_harabasz_score(np.ones((10, 2)), (([0] * 5) + ([1] * 5))))
assert (0.0 == calinski_harabasz_score(([[(- 1), (- 1)], [1, 1... |
class _PreprocessorInfo(object):
def __init__(self, stack_before_if):
self.stack_before_if = stack_before_if
self.stack_before_else = []
self.seen_else = False |
class TinyNetwork(nn.Module):
def __init__(self, C, N, genotype, num_classes):
super(TinyNetwork, self).__init__()
self._C = C
self._layerN = N
self.channel = (1 if (num_classes == 18) else 3)
self.stem = nn.Sequential(nn.Conv2d(self.channel, C, kernel_size=3, padding=1, bias... |
def get_norm_layer(norm_type):
if (norm_type == 'batch'):
norm_layer = nn.BatchNorm2d
elif (norm_type == 'instance'):
norm_layer = nn.InstanceNorm2d
else:
print(('normalization layer [%s] is not found' % norm))
return norm_layer |
class LikeZapp(tvm.relay.dataflow_pattern.DFPatternCallback):
def __init__(self):
self.translations_with_dt = {'zeros_like': tvm.relay.zeros, 'ones_like': tvm.relay.ones}
self.data_tensor = tvm.relay.dataflow_pattern.wildcard()
self.pattern_tensor = tvm.relay.dataflow_pattern.wildcard()
... |
def append_replace_return_docstrings(model_class, output_type, config_class):
model_class.__call__ = copy_func(model_class.__call__)
model_class.__call__ = replace_return_docstrings(output_type=output_type, config_class=config_class)(model_class.__call__) |
def setup_logging(log_file='log.txt', resume=False, dummy=False):
if dummy:
logging.getLogger('dummy')
else:
if (os.path.isfile(log_file) and resume):
file_mode = 'a'
else:
file_mode = 'w'
root_logger = logging.getLogger()
if root_logger.handlers:
... |
def get_abi3_suffix():
for (suffix, _, _) in (s for s in imp.get_suffixes() if (s[2] == imp.C_EXTENSION)):
if ('.abi3' in suffix):
return suffix
elif (suffix == '.pyd'):
return suffix |
def get_margins(clusters: List[Cluster], min_occurances: int):
for c in clusters:
if (len(c) >= min_occurances):
return c
return clusters[0] |
class RK4(FixedGridODESolver):
order = 4
def _step_func(self, func, t0, dt, t1, y0):
f0 = func(t0, y0, perturb=(Perturb.NEXT if self.perturb else Perturb.NONE))
return (rk4_alt_step_func(func, t0, dt, t1, y0, f0=f0, perturb=self.perturb), f0) |
class PUndirNet(object):
thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag')
def __init__(self, *args, **kwargs):
raise AttributeError('No constructor defined')
__repr__ = _swig_repr
def New():
return _snap.PUndirNet_New()
New =... |
class ResultList():
def __init__(self, rule, name_generator):
self.final_effect = rule.effect
self.result = []
self.name_generator = name_generator
def get_result(self):
self.result[(- 1)].effect = self.final_effect
return self.result
def add_rule(self, type, conditio... |
def get_informed_denoiser(diffusion):
def informed_denoiser(model, noisy_data, noise_map, clip_denoised=False, model_kwargs=None, etaA_ddrm=1.0, etaB_ddrm=1.0):
device = next(model.parameters()).device
etaA_ddrm = torch.tensor(etaA_ddrm, device=device).float()
etaB_ddrm = torch.tensor(etaB_d... |
def _make_sdfg(node, parent_state, parent_sdfg, implementation):
arr_desc = node.validate(parent_sdfg, parent_state)
if node.overwrite:
(in_shape, in_dtype, in_strides, n) = arr_desc
else:
(in_shape, in_dtype, in_strides, out_shape, out_dtype, out_strides, n) = arr_desc
dtype = in_dtype
... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--seed', type=int, default=3, help='random seed')
parser.add_argument('--plot-interval', type=int, default=50, help='plot interval. 0 to disable plotting.')
parser.add_argument('--save-interval', type=int, default=50, help='interval to ... |
def set_seeds(seed):
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed) |
.parametrize('value, expected', (({'exclusiveMinimum': True, 'minimum': 5}, {'exclusiveMinimum': True, 'minimum': 5}), ({'exclusiveMinimum': 5}, {'exclusiveMinimum': True, 'minimum': 5}), ({'exclusiveMaximum': 5}, {'exclusiveMaximum': True, 'maximum': 5}), ({'schema': {'exclusiveMaximum': 5}}, {'schema': {'exclusiveMax... |
def list_functions():
fnames = set(GLOBALS).difference(KEYWORDS)
documented = Filtered(list(fnames), IsDocumentedWord)
return tuple(sorted(documented.sage())) |
.parametrize('param_range, xscale', [([5, 10, 15], 'linear'), ([(- 50), 5, 50, 500], 'symlog'), ([5, 50, 500], 'log')])
def test_validation_curve_xscale_from_param_range_provided_as_a_list(pyplot, data, param_range, xscale):
(X, y) = data
estimator = DecisionTreeClassifier(random_state=0)
param_name = 'max_... |
def GL(n, R, var='a'):
(degree, ring) = normalize_args_vectorspace(n, R, var='a')
try:
if ring.is_finite():
cat = Groups().Finite()
elif ((n > 1) or (ring in Fields())):
cat = Groups().Infinite()
else:
cat = Groups()
except AttributeError:
... |
def _toggle_dropout(cell_params, mode):
cell_params = copy.deepcopy(cell_params)
if (mode != tf.contrib.learn.ModeKeys.TRAIN):
cell_params['dropout_input_keep_prob'] = 1.0
cell_params['dropout_output_keep_prob'] = 1.0
return cell_params |
def select_indices(data_source: ds.PymiaDatasource, selection_strategy: SelectionStrategy):
selected_indices = []
for (i, sample) in enumerate(data_source):
if selection_strategy(sample):
selected_indices.append(i)
return selected_indices |
class PLBartForConditionalGeneration(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def get_kmeans_model(n_clusters, init, max_iter, batch_size, tol, max_no_improvement, n_init, reassignment_ratio, random_state):
return MiniBatchKMeans(n_clusters=n_clusters, init=init, max_iter=max_iter, batch_size=batch_size, tol=tol, max_no_improvement=max_no_improvement, n_init=n_init, reassignment_ratio=reassi... |
def get_tl_line_values_from_file_contents(content, CRLF=True, LTRB=True, withTranscription=False, withConfidence=False, imWidth=0, imHeight=0, sort_by_confidences=True):
pointsList = []
transcriptionsList = []
confidencesList = []
lines = content.split(('\r\n' if CRLF else '\n'))
for line in lines:
... |
_toolkit()
class InvestmentManager(FunctionToolkit):
name_for_human = 'Investment Manager'
description_for_human = 'Toolkit for managing personal investments.'
name_for_model = 'InvestmentManager'
description_for_model = 'A comprehensive toolkit for managing personal investments, including retrieving in... |
class QDynamicLinearBenchmark(_QLinearBenchmarkBase):
def init(self, N, IN, OUT, device):
super(QDynamicLinearBenchmark, self).init(N, IN, OUT, nnqd.Linear(IN, OUT))
self.input = self.X
self.set_module_name('QDynamicLinear') |
class Algorithm():
def get_params(self):
signature = inspect.signature(self.__class__.__init__)
params_exclude = ['self', 'random_state', 'verbose']
params = dict()
for param in signature.parameters.values():
name = param.name
if (name not in params_exclude):
... |
class LastKFramesSelector(Callable):
def __init__(self, k: int):
self.k = k
def __call__(self, frame_tss: FrameTsList) -> FrameTsList:
return frame_tss[(- self.k):] |
(datatype[N], datatype[N])
def jacobi1d(A, B):
for t in range(tsteps):
def a(i: _[1:(N - 1)]):
(a1 << A[(i - 1)])
(a2 << A[i])
(a3 << A[(i + 1)])
(b >> B[i])
b = (0.33333 * ((a1 + a2) + a3))
def b(i: _[1:(N - 1)]):
(a1 << B[(i -... |
def bert_masking(sentence, mask, tokens, pad, mask_id):
sentence = np.copy(sentence)
sent_length = len(sentence)
target = np.copy(sentence)
mask = set(mask)
for i in range(sent_length):
if (i in mask):
rand = np.random.random()
if (rand < 0.8):
sentenc... |
def infer_abbr(class_type):
def camel2snack(word):
word = re.sub('([A-Z]+)([A-Z][a-z])', '\\1_\\2', word)
word = re.sub('([a-z\\d])([A-Z])', '\\1_\\2', word)
word = word.replace('-', '_')
return word.lower()
if (not inspect.isclass(class_type)):
raise TypeError(f'class_ty... |
def seed_test_case2():
var0 = True
var1 = True
var2 = module0.i_take_bools(var0, var1)
assert (var2 == 'Bools are equal!') |
def scale_stats_container(sc, num_of_scaling_factors):
scaling_factor = np.random.random(num_of_scaling_factors)
scaled_sc = scale_statistics(sc, scaling_factor)
return (scaled_sc, scaling_factor) |
def test_initialize_from_files_not_lazy():
_pos = 'datasets/ToyFather/train/pos.pl'
_neg = 'datasets/ToyFather/train/neg.pl'
_facts = 'datasets/ToyFather/train/facts.pl'
_db = Database.from_files(pos=_pos, neg=_neg, facts=_facts, lazy_load=False)
assert isinstance(_db.pos, list)
assert isinstanc... |
class CryptoMiniSatEncoder(CNFEncoder):
group_counter = 0
def dimacs_encode_polynomial(self, p):
if ((p.deg() != 1) or (len(p) <= 1)):
res = super().dimacs_encode_polynomial(p)
else:
invert_last = bool(p.has_constant_part())
variables = list(p.vars_as_monomial... |
class SumMeter(Meter):
def __init__(self, round: Optional[int]=None):
self.round = round
self.reset()
def reset(self):
self.sum = 0
def update(self, val):
if (val is not None):
self.sum = (type_as(self.sum, val) + val)
def state_dict(self):
return {'su... |
def test_receiver_properties():
xyz_1 = np.c_[(0.0, 0.0, 0.0)]
xyz_2 = np.c_[(10.0, 0.0, 0.0)]
times = np.logspace((- 4), (- 2), 3)
rx = dc.receivers.BaseRx(xyz_1)
assert (rx.orientation is None)
rx = dc.receivers.BaseRx(xyz_1, orientation='x')
assert (rx.orientation == 'x')
with pytest.... |
def test_contraction_perturbation():
data_augmenter = DataAugmenter(perturbations=[ContractionPerturbation()])
instance: Instance = Instance(id='id0', input=Input(text='She is a doctor, and I am a student'), references=[Reference(Output(text='he is a teacher'), tags=[])])
instances: List[Instance] = data_au... |
class ConsoleFormatter(logging.Formatter):
def __init__(self, fmt=None, datefmt=None):
super(ConsoleFormatter, self).__init__(fmt=fmt, datefmt=datefmt)
def format(self, record=None):
indent = sys.modules[__name__].global_indent
record.msg = ((' ' * indent) + record.msg)
return su... |
class BP1SNmat(SpectralMatrix):
def assemble(self, method):
from shenfun.jacobi.recursions import Lmat, half, cn
(test, trial) = (self.testfunction, self.trialfunction)
assert isinstance(test[0], P1)
assert isinstance(trial[0], SN)
N = (test[0].N - 2)
K = trial[0].ste... |
def move_directory(src_dir, dst_dir):
print('Moving to {}'.format(dst_dir))
os.makedirs(dst_dir, exist_ok=True)
for file_name in os.listdir(src_dir):
os.rename(os.path.join(src_dir, file_name), os.path.join(dst_dir, file_name)) |
def test_schema_consistency():
data_dir = sys.argv[1]
db_name = 'flight_2'
schema_graphs = load_schema_graphs_spider(data_dir, 'spider')
schema = schema_graphs[db_name]
schema.pretty_print()
in_sql = 'SELECT singer.Name FROM concert JOIN singer_in_concert ON singer_in_concert.Singer_ID = singer.... |
class EvalConsumer(Consumer):
def __init__(self, dataset, data_sequencer, support, disk_images=True):
self.dataset = dataset
self.data_sequencer = data_sequencer
self.support = support
self.disk_images = disk_images
super().__init__()
def consume(self, inputs):
if... |
def get_random_predictions(reference_file, preds_per_sent=3, do_eval=False):
ref_df = pd.read_csv(reference_file)
if do_eval:
ce_metric = load_metric('seqeval')
sig_metric = load_metric('seqeval')
refs = [get_BIO_all(i) for i in ref_df['text_w_pairs']]
else:
refs = [get_BIO_a... |
def collect_dataframes(run_id_to_filename_dictionary):
loaded_dataframes = {}
for (k, v) in run_id_to_filename_dictionary.items():
loaded_dataframes[k] = pd.read_csv(v)
return loaded_dataframes |
def get_auto_soundness_ret_types_offsets_and_casts(func: LeanFunctionInfo, lean_info: LeanProgramInfo, cast_end_separator: str='') -> List[Tuple[(CairoType, int, str)]]:
end_offset = 0
explicit_offsets_etc = lean_info.struct_defs.get_offsets_and_casts_by_types(func.func_scope, func.ret_arg_types, end_offset, le... |
def test_superb_sid():
with tempfile.TemporaryDirectory() as tempdir:
with pseudo_audio([10, 2, 1, 8, 5]) as (wav_paths, num_samples):
class TestSID(SuperbSID):
def default_config(self) -> dict:
config = super().default_config()
config['pre... |
def test_from_cupy():
cupy_array_1d = cp.arange(10)
cupy_array_2d = cp.array([[1.1, 2.2], [3.3, 4.4], [5.5, 6.6], [7.7, 8.8]])
ak_cupy_array_1d = ak.from_cupy(cupy_array_1d)
ak_cupy_array_2d = ak.from_cupy(cupy_array_2d)
for i in range(10):
assert (ak_cupy_array_1d[i] == cupy_array_1d[i])
... |
def get_identifier(s):
if ('identifier=' == s[:11]):
return ('SimpleName_' + s[11:])
else:
return None |
def integrate(expression, v=None, a=None, b=None, algorithm=None, hold=False):
(expression, v, a, b) = _normalize_integral_input(expression, v, a, b)
if (algorithm is not None):
integrator = available_integrators.get(algorithm)
if (not integrator):
raise ValueError(('Unknown algorith... |
def train(args, model, tokenizer, ngram_dict, processor, label_list):
train_dataset = load_examples(args, tokenizer, ngram_dict, processor, label_list, mode='train')
if args.fp16:
model.half()
if (args.local_rank != (- 1)):
try:
from apex.parallel import DistributedDataParallel a... |
def kmax_pooling(inputs, dim, k):
indices = inputs.topk(k, dim=dim)[1].sort(dim=dim)[0]
return inputs.gather(dim, indices) |
class MnistShardDescriptor(ShardDescriptor):
def __init__(self, rank_worldsize: str='1, 1', **kwargs) -> None:
(self.rank, self.worldsize) = tuple((int(num) for num in rank_worldsize.split(',')))
((x_train, y_train), (x_val, y_val)) = self.download_data()
self.data_by_type = {'train': (x_tra... |
def register_Ns3LteEnbComponentCarrierManager_methods(root_module, cls):
cls.add_constructor([param('ns3::LteEnbComponentCarrierManager const &', 'arg0')])
cls.add_constructor([])
cls.add_method('GetLteCcmMacSapUser', 'ns3::LteCcmMacSapUser *', [], is_virtual=True)
cls.add_method('GetLteCcmRrcSapProvide... |
class Attention(nn.Module):
def __init__(self, dim, head, sr_ratio=1):
super().__init__()
self.head = head
self.sr_ratio = sr_ratio
self.scale = ((dim // head) ** (- 0.5))
self.q = nn.Linear(dim, dim, bias=True)
self.kv = nn.Linear(dim, (dim * 2), bias=True)
s... |
def _GetPrincipleQuantumNumber(atNum):
if (atNum <= 2):
return 1
elif (atNum <= 10):
return 2
elif (atNum <= 18):
return 3
elif (atNum <= 36):
return 4
elif (atNum <= 54):
return 5
elif (atNum <= 86):
return 6
else:
return 7 |
class data_reader():
def __init__(self, train_test_files, use_columns, output_file_name):
if (not os.path.exists(output_file_name)):
(self.data, self.idToLabel) = self.readPamap2(train_test_files, use_columns)
self.save_data(output_file_name)
def save_data(self, output_file_name)... |
class TransformerBaseline(nn.Module):
def init_weights(layer):
if (type(layer) == nn.Linear):
nn.init.xavier_normal_(layer.weight)
def __init__(self, config):
super(TransformerBaseline, self).__init__()
self.config = config
self.transformer_post = Transformer.Transfor... |
def get_mb_mpo_agent(dim_state, dim_action, params, reward_model, transformations, action_scale, input_transform=None, termination_model=None, initial_distribution=None):
dynamical_model = _get_model(dim_state, dim_action, params, input_transform, transformations)
model_optimizer = optim.Adam(dynamical_model.pa... |
def ResNet34(num_classes=10):
return ResNet(BasicBlock, layers=[3, 4, 6, 3], filters=[64, 128, 256, 512], num_classes=num_classes) |
class DatasetEvaluator():
def reset(self):
pass
def preprocess_inputs(self, inputs):
pass
def process(self, inputs, outputs):
pass
def evaluate(self):
pass |
def AztecDiamondGraph(n):
from sage.graphs.generators.basic import Grid2dGraph
if n:
N = (2 * n)
G = Grid2dGraph(N, N)
H = G.subgraph([(i, j) for i in range(N) for j in range(N) if (((i - n) <= j <= (n + i)) and (((n - 1) - i) <= j <= (((3 * n) - i) - 1)))])
else:
H = Graph()... |
class GroupOps(object):
def identity():
_res = ([0.0] * 4)
_res[0] = 0
_res[1] = 0
_res[2] = 0
_res[3] = 1
return sym.Unit3.from_storage(_res)
def inverse(a):
_a = a.data
_res = ([0.0] * 4)
_res[0] = (- _a[0])
_res[1] = (- _a[1])
... |
def main():
if (sys.argv[1] == 'delex'):
print('MultiWoz Create delexicalized dialogues. Get yourself a coffee, this might take a while.')
if (not os.path.isfile(os.path.join(DATA_DIR, 'multi-woz/delex.json'))):
data = createDelexData()
else:
data = json.load(open(os.... |
def _get_word_cluster_features(query_tokens, clusters_name, resources):
if (not clusters_name):
return []
ngrams = get_all_ngrams(query_tokens)
cluster_features = []
for ngram in ngrams:
cluster = get_word_cluster(resources, clusters_name).get(ngram[NGRAM].lower(), None)
if (clus... |
def get_module_type(graph):
if (not graph.is_connected()):
return NodeType.PARALLEL
elif graph.complement().is_connected():
return NodeType.PRIME
return NodeType.SERIES |
def ref_pow2_quantize(x, sign, with_zero, n, m, quantize, ste_fine_grained):
assert (n > 0)
n_ = ((n - 1) if sign else n)
n_ = ((n_ - 1) if with_zero else n_)
ref_p_max = (2 ** m)
ref_p_min = (2 ** (m - ((1 << n_) - 1)))
ref_pruning_threshold = (ref_p_min * (2.0 ** (- 0.5)))
if quantize:
... |
def changeEgoInTwoStar(G, A, i):
return (((G.indegree(i) * (G.indegree(i) - 1)) / 2.0) if (G.indegree(i) > 1) else 0) |
def kmeans_tensor(tensor_data: np.ndarray, p: int, n_bits: int, per_channel: bool=False, channel_axis: int=1, n_iter: int=10, min_threshold: float=MIN_THRESHOLD, quant_error_method: qc.QuantizationErrorMethod=None) -> dict:
if (len(np.unique(tensor_data.flatten())) < (2 ** n_bits)):
n_clusters = len(np.uniq... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.