code stringlengths 101 5.91M |
|---|
class FiniteFieldPointEnumerator(NaiveFinitePointEnumerator):
_method
def multiplicative_generator(self):
return self.ring.multiplicative_generator()
_method
def multiplicative_group_order(self):
return self.ring.multiplicative_generator().multiplicative_order()
_method
def root_... |
class Blip2Base(BaseModel):
def init_tokenizer(cls, truncation_side='right'):
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', truncation_side=truncation_side)
tokenizer.add_special_tokens({'bos_token': '[DEC]'})
return tokenizer
def maybe_autocast(self, dtype=torch.float16... |
.parametrize('inspecs', inspecs_params())
.parametrize('shared', [True, False])
def test_activation(inspecs, shared, nnabla_opts):
fb = FunctionBenchmark(PF.prelu, inspecs, [1], {}, nnabla_opts.ext, nnabla_opts.ext_kwargs)
fb.benchmark()
fb.write(writer=nnabla_opts.function_benchmark_writer) |
def read_mask_file(filepath, out):
f = open(filepath, 'rb')
dat = zlib.decompress(f.read())
out[:] = np.frombuffer(dat, dtype=bool).reshape((480, 480))
f.close() |
class Hovmoller():
def __init__(self, kwrgs_load: dict=None, slice_dates: tuple=None, event_dates: pd.DatetimeIndex=None, lags_prior: int=None, lags_posterior: int=None, standardize: bool=False, seldates: tuple=None, rollingmeanwindow: int=None, name=None, zoomdim: tuple=None, ignore_overlap_events: bool=False, t_t... |
class GraphTransformerNet(nn.Module):
def __init__(self, net_params):
super().__init__()
num_atom_type = net_params['num_atom_type']
num_bond_type = net_params['num_bond_type']
hidden_dim = net_params['hidden_dim']
num_heads = net_params['n_heads']
out_dim = net_param... |
def make_sequence_example(inputs, labels, genders):
input_features = [tf.train.Feature(float_list=tf.train.FloatList(value=input_)) for input_ in inputs]
label_features = [tf.train.Feature(float_list=tf.train.FloatList(value=label)) for label in labels]
gender_features = [tf.train.Feature(float_list=tf.trai... |
class IntBinopNode(NumBinopNode):
def c_types_okay(self, type1, type2):
return ((type1.is_int or type1.is_enum) and (type2.is_int or type2.is_enum)) |
def format_assignments(assignments, num_workers=1, log_every=1000, verbose=False):
clustering_types = sorted(list(assignments[0].keys()))
format_assignment = partial(_format_assignment, clustering_types=clustering_types)
assignments = list(multiprocess(format_assignment, assignments, num_workers, 'formattin... |
def sim_ball_traj(init_pos=np.zeros(3), init_vel=np.array([(- 1.3), 4.5, 2.2]), lin_air_drag=np.array([0.0, 0.0, 0.0]), quad_air_drag=0.0, bounce_fac=np.array([0.9, 0.9, 0.8]), deltaT=0.005, T=120, max_bounces=None):
x = init_pos
xd = init_vel
obs = []
vel = []
time = []
is_bounce = []
bounc... |
def _polar_graph(m, q, g, intersection_size=None):
from sage.libs.gap.libgap import libgap
from itertools import combinations
W = libgap.FullRowSpace(libgap.GF(q), m)
B = libgap.Elements(libgap.Basis(W))
V = libgap.Orbit(g, B[0], libgap.OnLines)
gp = libgap.Action(g, V, libgap.OnLines)
s = l... |
class CategoryEncoder():
def __init__(self, category: List[str]) -> None:
self.category = list(sorted(set(category)))
def __len__(self) -> int:
return len(self.category)
def encode(self, label: str) -> int:
return self.category.index(label)
def decode(self, index: int) -> str:
... |
def convert(name, in_dir, out_dir, resolution, skip_existing):
out_name = f'{name[0]}/{name}'
out_filename = (out_dir / f'{out_name}.json')
if (skip_existing and out_filename.is_file()):
return
music = muspy.read(((in_dir / name[0]) / f'{name}.mid'))
adjust_resolution(music, resolution)
... |
def validate_strategy_specs(specs: Dict[(str, StrategySpec)]):
for (rid, spec) in specs.items():
if (len(spec) < 1):
raise ValueError(f'Empty spec for runtime_id={rid}')
expected_prob_list = spec.meta_data.get('prob_list', ([(1 / len(spec))] * len(spec)))
if (expected_prob_list i... |
.parametrize('func', [ak.str.is_alnum, ak.str.is_alpha, ak.str.is_ascii, ak.str.is_decimal, ak.str.is_digit, ak.str.is_lower, ak.str.is_numeric, ak.str.is_printable, ak.str.is_space, ak.str.is_title, ak.str.is_upper, ak.str.capitalize, ak.str.lower, ak.str.upper, ak.str.reverse, ak.str.swapcase, ak.str.title, ak.str.lt... |
class SmoothTriangle(Triangle):
def __init__(self, a, b, c, da, db, dc, color=0):
self._a = a
self._b = b
self._c = c
self._da = da
self._db = db
self._dc = dc
self._color = color
def str(self):
return ('%s %s %s %s %s %s %s' % (self._a, self._b, s... |
def run_chunks_node(node_rank, cfg):
(args, chunks, num_chunks) = cfg
args.node_rank = node_rank
chunks = chunks[node_rank]
if args.computation.load_async:
run_async(args, chunks, node_rank)
else:
for (i, chunk) in enumerate(chunks):
(num, chunk) = chunk
print... |
_utils.test(arch=archs_support_ndarray_ad, require=ti.extension.adstack)
def test_multiple_ib_mixed():
x = ti.ndarray(float, (), needs_grad=True)
y = ti.ndarray(float, (), needs_grad=True)
def compute_y(x: ti.types.ndarray(), y: ti.types.ndarray()):
for j in range(2):
for i in range(3):
... |
class GroupNorm(nn.Module):
def __init__(self, num_groups, num_channels, eps=1e-05, affine=True):
super().__init__()
self.num_groups = num_groups
self.num_channels = num_channels
self.eps = eps
self.affine = affine
if self.affine:
self.weight = nn.Paramete... |
def run_selection(args, chunk):
(data, metas, node_rank, i) = chunk
print('running chunk {}_{}'.format(node_rank, i))
res = _run_selection(args, data)
save_chunk_cache(args, node_rank, i, res, metas) |
def test_pixel_decoder():
base_channels = 64
pixel_decoder_cfg = ConfigDict(dict(type='PixelDecoder', in_channels=[(base_channels * (2 ** i)) for i in range(4)], feat_channels=base_channels, out_channels=base_channels, norm_cfg=dict(type='GN', num_groups=32), act_cfg=dict(type='ReLU')))
self = build_plugin_... |
def test_optimize_2d():
with goos.OptimizationPlan() as plan:
x = goos.Variable([[1, 2], [3, 4]])
obj = ((goos.Norm((x - goos.Constant([[3, 2], [(- 4), 2]]))) ** 2) + 3)
goos.opt.scipy_minimize(obj, method='L-BFGS-B')
plan.run()
np.testing.assert_almost_equal(x.get().array, [... |
.parametrize('location, schema', ([(location, OBJECT_SCHEMA) for location in sorted(LOCATION_TO_CONTAINER)] + [('body', EMPTY_OBJECT_SCHEMA), ('body', ARRAY_SCHEMA), ('body', INTEGER_SCHEMA)]))
(data=st.data())
(deadline=None, suppress_health_check=SUPPRESSED_HEALTH_CHECKS, max_examples=MAX_EXAMPLES)
def test_top_level... |
def match_filtering(new_turn, ori_turn, sentences):
ori_turn_label_set = set()
for (slot, value) in ori_turn['turn_label']:
ori_turn_label_set.add(((slot + '-') + value))
new_turn_label_set = set()
for (slot, value) in new_turn['turn_label']:
new_turn_label_set.add(((slot + '-') + value)... |
class BasicTransform(nn.Module):
def __init__(self, w_in, w_out, stride, norm, activation_class, _params):
super().__init__()
self.a = conv2d(w_in, w_out, 3, stride=stride)
self.a_bn = get_norm(norm, w_out)
self.a_af = activation_class()
self.b = conv2d(w_out, w_out, 3)
... |
class Dataset():
def __init__(self, name, path=None, vec=None, args=None):
self.name = name
if ((args is not None) and (path is not None) and hasattr(args, 'data_dir')):
path = os.path.join(args.data_dir, path)
self.vec = (pickle.load(open(path, 'rb')) if (vec is None) else vec)
... |
def config_parser():
parser = configargparse.ArgParser()
parser.add_argument('--config', is_config_file=True, help='config file path')
parser.add_argument('--expname', type=str, help='experiment name')
parser.add_argument('--basedir', type=str, default='./logs/', help='where to store ckpts and logs')
... |
def test_run_diagnostic():
data1 = pd.DataFrame({'col': [1, 2, 3]})
data2 = pd.DataFrame({'col': [2, 1, 3]})
metadata = SingleTableMetadata()
metadata.add_column('col', sdtype='numerical')
DiagnosticReport.generate = Mock(return_value=123)
run_diagnostic(data1, data2, metadata)
DiagnosticRep... |
class Enumeration(EntryBase):
def __init__(self, j):
super().__init__(j, 'enumeration')
if ('inc_cases' in j):
self.cases = load_inc_enums()[j['inc_cases']]
else:
self.cases = dict(((Name(name), value) for (name, value) in j['cases'].items())) |
def multiplicative_sequence(q, n=None):
from sage.combinat.sf.sf import SymmetricFunctions
from sage.combinat.partition import Partitions
from sage.misc.misc_c import prod
if (n is None):
n = q.degree()
R = q.parent().base_ring()
Sym = SymmetricFunctions(R)
m = Sym.m()
mon_pol = ... |
class FactualConsistencyScorer(Scorer):
def __init__(self, align, aggr_type='mean', device='cuda'):
Scorer.__init__(self, align=align, aggr_type=aggr_type, device=device)
def score(self, grounding, hypo, aspect='consistency', remove_stopwords=False):
kwargs = dict(grounding=grounding, hypo=hypo,... |
def create_model():
logger = logging.getLogger(__name__)
start_iter = 0
checkpoints = {}
output_dir = get_output_dir(cfg.TRAIN.DATASETS, training=True)
weights_file = cfg.TRAIN.WEIGHTS
if cfg.TRAIN.AUTO_RESUME:
final_path = os.path.join(output_dir, 'model_final.pkl')
if os.path.e... |
class GradualStyleEncoder(Module):
def __init__(self, num_layers, mode='ir', input_channels=3, opts=None):
super(GradualStyleEncoder, self).__init__()
assert (num_layers in [50, 100, 152]), 'num_layers should be 50,100, or 152'
assert (mode in ['ir', 'ir_se']), 'mode should be ir or ir_se'
... |
def mvStraight(speed, angle, verbose=0):
vel_msg = Twist()
angular_speed = (((speed * 2) * PI) / 360)
relative_angle = (((angle * 2) * PI) / 360)
vel_msg.linear.x = angular_speed
t0 = rospy.Time.now().to_sec()
current_angle = 0
if (angle == (- 1)):
printv('inf mode : go straight inf ... |
class DinatModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class TFElectraForTokenClassification():
def __init__(self, *args, **kwargs):
requires_tf(self)
def from_pretrained(self, *args, **kwargs):
requires_tf(self) |
def get_cifar_100_just_x_or_y_ds(transform, train, **kw):
just = kw['just']
DATA_DIR = kw.get('DATA_DIR', DEFAULT_DATA_DIR)
just = just.lower()
if (just == 'x'):
ds_X = CIFAR100JustX(root=DATA_DIR, download=DOWNLOAD, train=train, transform=transform)
return ds_X
elif (just == 'y'):
... |
class ToTensor(object):
def __call__(self, sample):
img = np.array(sample['image']).astype(np.float32).transpose((2, 0, 1))
mask = np.expand_dims(np.array(sample['label']).astype(np.float32), (- 1)).transpose((2, 0, 1))
img = torch.from_numpy(img).float()
mask = torch.from_numpy(mask... |
def get_gatk_bin():
bin = get_param(['software', 'gatk3_jar'], 'GenomeAnalysisTK.jar')
if (bin[(- 4):] == '.jar'):
bin = 'java -XX:ParallelGCThreads={threads} -XX:+UseParallelGC -XX:-UsePerfData -Xms{resources.memory}m -Xmx{resources.memory}m -jar bin'
return bin |
class Refvg(object):
def __init__(self, split, model_method):
self._dataset = 'refvg'
self._imageset = 'vg'
self._split = split
self._ref_db = Refer(opt['data_root'], self._dataset, split)
if (model_method == 'sgmn'):
self._ref_sg = self._load_sg()
sel... |
def _remove_if_exists(path):
if os.path.exists(path):
if os.path.isfile(path):
os.remove(path)
else:
shutil.rmtree(path) |
def get_model(args):
print(f'Creating model: {args.model}')
model = create_model(args.model, pretrained=False, drop_path_rate=args.drop_path, drop_block_rate=None, decoder_depth=args.decoder_depth, use_cls_token=args.use_cls_token, num_frames=args.num_frames, target_feature_dim=args.distillation_target_dim, tar... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('language', help='Language to download')
parser.add_argument('--output', default='oscar_dump', help='Path for saving files')
parser.add_argument('--no_xz', dest='xz', default=True, action='store_false', help="Don't xz the files - d... |
class Lgplvm(Gplvm):
name = 'Lgplvm'
def __init__(self, n: int, m: int, d: int, n_samples: int, lat_dist: Rdist, lprior: Lprior, Bayesian=True, Y=None, learn_neuron_scale=False, ard=False, learn_scale=None, sigma=None, C=None):
obs = (Bfa(n, d, Y=Y, learn_neuron_scale=learn_neuron_scale, ard=ard, learn_... |
def apply_random_mask(message_bits, input_key, sample_seed_prefix, input_nonce):
mask_generator = DRBG(input_key, (sample_seed_prefix + input_nonce))
mask_bits = mask_generator.generate_bits(len(message_bits))
masked_message_bits = deepcopy(message_bits)
for b in range(0, len(message_bits)):
mas... |
class BayesBiNN(Optimizer):
def __init__(self, model, train_set_size, lr=1e-09, betas=0.0, prior_lamda=None, num_samples=5, lamda_init=10, lamda_std=0, temperature=1, reweight=1):
if (lr <= 0.0):
raise ValueError('Invalid learning rate: {}'.format(lr))
if ((prior_lamda is not None) and (... |
def _format_custom_logs(keys=[], raw_log={}, _type=REWARD):
log = {}
if keys:
for key in keys:
if (key in raw_log):
log[key] = raw_log[key]
else:
log = raw_log
log[TYPE] = _type
return _format_log(log) |
def generate_json(folder_path, split):
yaml_file = read_file((((folder_path + '/') + split) + '.yaml'))
translations_file = read_file((((folder_path + '/') + split) + '.fra'))
assert (len(yaml_file) == len(translations_file))
output_json = dict()
for i in range(len(yaml_file)):
content = yam... |
def split_entities(entity_list, add_fraction):
print((('splitting for additional ' + str(add_fraction)) + ' entities'))
num_entities = len(entity_list)
num_new_entities = np.round((num_entities * add_fraction))
entity_splits_dict = {}
for entity in entity_list:
entity_splits_dict[tuple(entit... |
def load_ply_normal(filename, point_num):
plydata = PlyData.read(filename)
pc = plydata['normal'].data[:point_num]
pc_array = np.array([[x, y, z] for (x, y, z) in pc])
return pc_array |
class Polynomial_padic_capped_relative_dense(Polynomial_generic_cdv, Polynomial_padic):
def __init__(self, parent, x=None, check=True, is_gen=False, construct=False, absprec=infinity, relprec=infinity):
Polynomial.__init__(self, parent, is_gen=is_gen)
self._polygon = None
parentbr = parent.b... |
class CvtIntermediate(nn.Module):
def __init__(self, embed_dim, mlp_ratio):
super().__init__()
self.dense = nn.Linear(embed_dim, int((embed_dim * mlp_ratio)))
self.activation = nn.GELU()
def forward(self, hidden_state):
hidden_state = self.dense(hidden_state)
hidden_state... |
def copy_dory_subset():
testdata = relative_file('data/dory-subset.fa')
shutil.copyfile(testdata, 'dory-subset.fa')
testdata = relative_file('data/dory-subset.fq')
shutil.copyfile(testdata, 'dory-subset.fq') |
class SNLIBertPipe(MatchingBertPipe):
def process_from_file(self, paths=None):
data_bundle = SNLILoader().load(paths)
return self.process(data_bundle) |
def sharp_switch(extr, primary, *params):
primary = primary.strip()
found = False
default = None
rvalue = None
lvalue = ''
for param in params:
pair = param.split('=', 1)
lvalue = extr.expand(pair[0].strip())
rvalue = None
if (len(pair) > 1):
rvalue = ... |
class BaseCommandParser():
def __init__(self):
self.__attr_names = [name for (name, _, _) in self._desc_]
last_desc = self._desc_[0]
for d in self._desc_:
if (last_desc[1] < d[1]):
last_desc = d
def parse(self, buf, max_num):
desc = self._desc_
... |
class TestDeterministicIntentParser(FixtureTest):
def setUp(self):
super(TestDeterministicIntentParser, self).setUp()
slots_dataset_stream = io.StringIO('\n---\ntype: intent\nname: dummy_intent_1\nslots:\n - name: dummy_slot_name\n entity: dummy_entity_1\n - name: dummy_slot_name2\n entity: ... |
def directed_RNN(layer, recur_size, seq_lengths, bidirectional=True, recur_cell=LSTM, **kwargs):
bilin = kwargs.pop('bilin', False)
if bidirectional:
return BiRNN(layer, recur_size, seq_lengths, recur_cell=recur_cell, bilin=bilin, **kwargs)
else:
return UniRNN(layer, recur_size, seq_lengths,... |
def get_nonlinearity_for_embedding():
if (args.nonlinearity_for_embedding == 'relu'):
return tf.nn.relu
if (args.nonlinearity_for_embedding == 'tanh'):
return tf.nn.tanh
assert False |
class SimilarityClassTypes(UniqueRepresentation, Parent):
def __classcall_private__(cls, n, min=None):
if (min is None):
min = PrimarySimilarityClassType(1, Partition([1]))
if isinstance(min, list):
min = PrimarySimilarityClassType(min[0], min[1])
if (not isinstance(m... |
def test_find_dependencies_with_zero_round(tensor_key):
tensor_codec = TensorCodec(NoCompressionPipeline())
(tensor_name, origin, round_number, report, tags) = tensor_key
tensor_key = TensorKey(tensor_name, origin, round_number, report, ('model',))
tensor_key_dependencies = tensor_codec.find_dependencie... |
def start_client(args):
init_time_start = time.time()
time.sleep(WAIT_TIME)
args.gpu = [(- 1)]
args.mix_cpu_gpu = False
args.async_update = False
args.rel_part = False
args.strict_rel_part = False
args.soft_rel_part = False
args.valid = False
total_machine = get_machine_count(arg... |
def dump_conv2d(name='Conv2d_1a_3x3'):
conv_operation = sess.graph.get_operation_by_name((('InceptionResnetV2/' + name) + '/Conv2D'))
weights_tensor = sess.graph.get_tensor_by_name((('InceptionResnetV2/' + name) + '/weights:0'))
weights = weights_tensor.eval()
padding = make_padding(conv_operation.get_a... |
.experimental
.parametrize('batch_size', BATCH_SIZES)
def test_critic_forward(ddpg_critic_param, batch_size):
(critic, param) = ddpg_critic_param
state_dim = param['state_repr_dim']
action_dim = param['action_emb_dim']
state = torch.rand((batch_size, state_dim))
action = torch.rand((batch_size, acti... |
def desolve_rk4(de, dvar, ics=None, ivar=None, end_points=None, step=0.1, output='list', **kwds):
if (ics is None):
raise ValueError('No initial conditions, specify with ics=[x0,y0].')
if (output not in ['list', 'plot', 'slope_field']):
raise ValueError("Option output should be 'list', 'plot' or... |
def _propagate_node(dfg_state, node):
if isinstance(node, nodes.EntryNode):
internal_edges = [e for e in dfg_state.out_edges(node) if (e.src_conn and e.src_conn.startswith('OUT_'))]
external_edges = [e for e in dfg_state.in_edges(node) if (e.dst_conn and e.dst_conn.startswith('IN_'))]
getico... |
def test_list_files(workspace: Workspace, test_directory: Path, agent: Agent):
file_a = workspace.get_path('file_a.txt')
file_b = workspace.get_path('file_b.txt')
with open(file_a, 'w') as f:
f.write('This is file A.')
with open(file_b, 'w') as f:
f.write('This is file B.')
if (not o... |
class ImageLogger(Callback):
def __init__(self, batch_frequency, max_images, clamp=True, increase_log_steps=True, rescale=True, disabled=False, log_on_batch_idx=False, log_first_step=False, log_images_kwargs=None):
super().__init__()
self.rescale = rescale
self.batch_freq = batch_frequency
... |
class TypedArrayBuilder():
def __init__(self, form):
self.form = form
self.vm = awkward.forth.ForthMachine32('\n input data\n output part0-node0-offsets int64\n output part0-node2-data float64\n output part0-node3-offsets int64\n output part0-no... |
class TestRL2Worker(TfGraphTestCase):
def test_rl2_worker(self):
env = GarageEnv(DummyBoxEnv(obs_dim=(1,)))
policy = DummyPolicy(env_spec=env.spec)
worker = RL2Worker(seed=1, max_path_length=100, worker_number=1, n_paths_per_trial=5)
worker.update_agent(policy)
worker.update_... |
def tensors(n, min_dim=1, max_dim=4, dtype=np.float32, elements=None, **kwargs):
dims_ = st.lists(dims(**kwargs), min_size=min_dim, max_size=max_dim)
return dims_.flatmap((lambda dims: st.lists(arrays(dims, dtype, elements), min_size=n, max_size=n))) |
def main():
config = DavisConfig()
config.display()
seq_root = '../prepare/DAVIS_2017/JPEGImages/480p/carousel/'
dataLoader = DataLoader('../prepare/mask_rcnn_result/carousel.json')
obj_id = 0
mht = MHT(config, dataLoader, 'carousel')
for i in range(len(dataLoader.content)):
content_... |
def get_cookie_header(jar, request):
r = MockRequest(request)
jar.add_cookie_header(r)
return r.get_new_headers().get('Cookie') |
_BUILDERS.register_module()
class LayerDecayOptimizerConstructor(DefaultOptimizerConstructor):
def _validate_cfg(self):
if ('custom_keys' in self.paramwise_cfg):
if (not isinstance(self.paramwise_cfg['custom_keys'], dict)):
raise TypeError(f"If specified, custom_keys must be a di... |
def gelu(input_tensor):
cdf = (0.5 * (1.0 + tf.erf((input_tensor / tf.sqrt(2.0)))))
return (input_tensor * cdf) |
(scope='package')
def cfg_train_global() -> DictConfig:
with initialize(version_base='1.2', config_path='../configs'):
cfg = compose(config_name='train.yaml', return_hydra_config=True, overrides=[])
with open_dict(cfg):
cfg.paths.root_dir = str(pyrootutils.find_root())
cfg.tr... |
class EdgeMatcher(edge_matcher.BaseEdgeMatcher):
def __init__(self, source_matcher: BaseNode, target_matcher: BaseNode):
super().__init__(source_matcher, target_matcher)
def apply(self, input_object: Any) -> bool:
if (isinstance(input_object, tuple) and (len(input_object) >= 2)):
ret... |
def writeInfoToFile(log_file, info):
fh = open(log_file, 'w', encoding='utf-8')
fh.write((info + '\r\n'))
fh.flush()
fh.close() |
def register_Ns3LteSpectrumPhy_methods(root_module, cls):
cls.add_constructor([])
cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True)
cls.add_method('DoDispose', 'void', [], is_virtual=True)
cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SpectrumChannel >', 'c')], is_virtual=True... |
def get_logger(log_path, name='default'):
logger = logging.getLogger(name)
logger.propagate = False
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(message)s')
sh = logging.StreamHandler(sys.stdout)
sh.setFormatter(formatter)
logger.addHandler(sh)
fh = logging.FileHandler... |
def load_splitter(path: str) -> Splitter:
spark = State().session
args = spark.read.json(join(path, 'init_args.json')).first().asDict()
name = args['_splitter_name']
del args['_splitter_name']
splitter = globals()[name]
return splitter(**args) |
class ParsedDate():
def __init__(self) -> None:
self.ymd: Dict[(str, int)] = {'year': (- 1), 'month': (- 1), 'day': (- 1)}
self.hms: Dict[(str, int)] = {'hour': (- 1), 'minute': (- 1), 'second': (- 1)}
self.weekday: int = (- 1)
self.tzinfo: Dict[(str, Union[(int, str)])] = {'timezone... |
class Partition3(nn.Module):
LAYER_SCOPES = ['T5ForConditionalGeneration/T5Stack[decoder]/Dropout[dropout]', 'T5ForConditionalGeneration/T5Stack[decoder]/T5Block[0]', 'T5ForConditionalGeneration/T5Stack[decoder]/T5Block[1]', 'T5ForConditionalGeneration/T5Stack[decoder]/T5Block[2]', 'T5ForConditionalGeneration/T5Sta... |
def load_data(config):
print(('-*-' * 10))
print('current data_sign: {}'.format(config.data_sign))
if (config.data_sign == 'conll03'):
data_processor = Conll03Processor()
elif (config.data_sign == 'zh_msra'):
data_processor = MSRAProcessor()
elif (config.data_sign == 'zh_onto'):
... |
def _script_local_optimizer_step(local_optim_rref: RRef[_ScriptLocalOptimizerInterface], autograd_ctx_id: int) -> None:
local_optim = local_optim_rref.local_value()
local_optim.step(autograd_ctx_id) |
def Q8():
E = 'abcdefgh'
CC = {3: ['abfg', 'bcdg', 'defg', 'cdeh', 'aefh', 'abch', 'abed', 'cfgh', 'bcef', 'adgh', 'acdf'], 4: [E]}
M = CircuitClosuresMatroid(groundset=E, circuit_closures=CC)
M.rename(('Q8: ' + repr(M)))
return M |
def resplit_mwt(tokens, pipeline, keep_tokens=True):
if ('tokenize' not in pipeline.processors):
raise ValueError('Need a Pipeline with a valid tokenize processor')
if ('mwt' not in pipeline.processors):
raise ValueError('Need a Pipeline with a valid mwt processor')
tokenize_processor = pipe... |
class GenericAccessibleObject(metaclass=abc.ABCMeta):
def __init__(self, owner: (TypeInfo | None)):
self._owner = owner
def generated_type(self) -> ProperType:
def owner(self) -> (TypeInfo | None):
return self._owner
def is_enum(self) -> bool:
return False
def is_method(self)... |
def main():
global num_bins, sampling_rate, num_centroids, percent
print('Opening video!')
capture = cv2.VideoCapture(os.path.abspath(os.path.expanduser(sys.argv[1])))
print('Video opened\nChoosing frames')
frames = []
i = 0
while capture.isOpened():
if ((i % sampling_rate) == 0):
... |
class TokenizeTest(absltest.TestCase):
def test_give_me_a_name(self):
self.assertEqual(['one', 'two', 'three'], tokenize.tokenize('one Two three', None))
self.assertEqual(['one', 'two', 'three'], tokenize.tokenize('one\n Two \nthree', None)) |
def cosine_rampdown_1(current, rampdown_length):
'Cosine rampdown from
assert (0 <= current <= rampdown_length)
return max(0.0, float((0.5 * (np.cos(((np.pi * current) / rampdown_length)) + 1)))) |
def is_type_list(x, type):
if (not isinstance(x, list)):
return False
return all((isinstance(item, type) for item in x)) |
class _DistributedDataParallel(torch.nn.parallel.DistributedDataParallel):
def __getattr__(self, name):
try:
return super().__getattr__(name)
except AttributeError:
return getattr(self.module, name) |
def _check_ip(val: Any, input_format: str, clean: bool) -> Any:
try:
if (val in NULL_VALUES):
return ((None, 'null') if clean else False)
address = ip_address(val)
vers = address.version
if (((vers == 4) and (input_format != 'ipv6')) or ((vers == 6) and (input_format != '... |
class UnetBlock_with_z(nn.Module):
def __init__(self, input_nc, outer_nc, inner_nc, nz=0, submodule=None, outermost=False, innermost=False, norm_layer=None, nl_layer=None, use_dropout=False, upsample='basic', padding_type='zero'):
super(UnetBlock_with_z, self).__init__()
p = 0
downconv = []
... |
_method_args
class SageSet(Set):
def __new__(cls, sage_set):
return Basic.__new__(cls, sage_set)
def _sage_(self):
return self._args[0]
def is_empty(self):
return self._sage_().is_empty()
def is_finite_set(self):
return self._sage_().is_finite()
def is_iterable(self):... |
.operations('success', 'failure', 'unsatisfiable')
def test_junitxml_file(cli, schema_url, hypothesis_max_examples, tmp_path):
xml_path = (tmp_path / 'junit.xml')
cli.run(schema_url, f'--junit-xml={xml_path}', f'--hypothesis-max-examples={(hypothesis_max_examples or 1)}', '--hypothesis-seed=1', '--checks=all')
... |
class TestEnum(JitTestCase):
def test_enum_value_types(self):
global IntEnum
class IntEnum(Enum):
FOO = 1
BAR = 2
global FloatEnum
class FloatEnum(Enum):
FOO = 1.2
BAR = 2.3
global StringEnum
class StringEnum(Enum):
... |
class Local_op(nn.Module):
def __init__(self, in_channels, out_channels):
super(Local_op, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=1, bias=False)
self.bn1 = nn.BatchNor... |
()
def get_text_between(cand):
start = (cand.person1_word_idx[1] + 1)
end = cand.person2_word_idx[0]
cand.text_between = ' '.join(cand.tokens[start:end])
return cand |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.