code stringlengths 101 5.91M |
|---|
def test_partial_max():
import functools
batch_size = 3
inp = torch.autograd.Variable(torch.rand(batch_size, 8))
torch_max = functools.partial(unittest.mock.Mock(wraps=torch.max), dim=(- 1))
torch_get = (lambda x, i: x[(range(x.shape[0]), i.view((- 1)))])
double = (lambda x: (x * 2))
batcher... |
def run(task: Task, num_samples: int, **kwargs: Any) -> torch.Tensor:
log = sbibm.get_logger(__name__)
if ('num_simulations' in kwargs):
log.warn('`num_simulations` was passed as a keyword but will be ignored, since this is a baseline method.')
prior = task.get_prior()
return prior(num_samples=n... |
def raw_reward_threshold(threshold):
def fn(metadata):
if (metadata['raw_reward'] > threshold):
return 1.0
elif (metadata['raw_reward'] > 0):
return (- 1)
return metadata['raw_reward']
return fn |
def async_execution(fn):
(fn)
def wrapper(*args, **kwargs):
return fn(*args, **kwargs)
wrapper._wrapped_async_rpc_function = fn
return wrapper |
_metaclass(ABCMeta)
class Model(object):
def __init__(self, do, du, horizon):
self.do = do
self.du = du
self.horizon = horizon
def train(self, rollouts):
pass
def encode(self, y, a):
pass
def decode(self, x):
pass
def get_dynamics(self):
pass
... |
class FiniteWordPath_triangle_grid_iter_with_caching(WordDatatype_iter_with_caching, FiniteWordPath_triangle_grid, FiniteWord_class):
pass |
class ByteMaskedArray(ByteMaskedMeta[Content], Content):
def __init__(self, mask, content, valid_when, *, parameters=None):
if (not (isinstance(mask, Index) and (mask.dtype == np.dtype(np.int8)))):
raise TypeError("{} 'mask' must be an Index with dtype=int8, not {}".format(type(self).__name__, r... |
def _refine_block(S, strong=False):
if (not S):
raise ValueError(('S (=%s) must be nonempty' % S))
if all(((s in ZZ) for s in S)):
X = sorted(S)
else:
X = sorted(S, key=str)
n = len(X)
out = []
if (not strong):
WordSet = IntegerListsLex(min_part=0, max_part=(n - 1... |
def _global_config_as_py_module_proxy_setup():
if (_PyModuleName in sys.modules):
return
sys.modules[_PyModuleName] = _GlobalConfigAsPyModuleProxy(_PyModuleName) |
_utils.test()
def test_ad_nested_for():
N = 5
loss = ti.field(float, shape=(), needs_grad=True)
def nested_for():
for i in range(N):
for j in range(N):
pass
with ti.ad.Tape(loss=loss):
nested_for() |
class Significance(object):
METHODS = {'permute': count_permutation_trials}
def __init__(self, systems, gold, trials=N_TRIALS, method='permute', n_jobs=1, metrics=['precision', 'recall', 'fscore'], fmt='none', measures=DEFAULT_MEASURE, type_weights=None):
if (len(systems) < 2):
raise ValueEr... |
class LinearLayer(nn.Module):
def __init__(self, input_dim, output_dim, act='relu', use_bn=False):
super(LinearLayer, self).__init__()
self.use_bn = use_bn
self.lin = nn.Linear(input_dim, output_dim)
self.act = (nn.ReLU() if (act == 'relu') else act)
if use_bn:
se... |
class BaseModel():
def modify_commandline_options(parser, is_train):
return parser
def name(self):
return 'BaseModel'
def initialize(self, opt):
self.opt = opt
self.gpu_ids = opt.gpu_ids
self.isTrain = opt.isTrain
self.device = (torch.device('cuda:{}'.format(s... |
_safe_enum
_enum
class TilingType(aenum.AutoNumberEnum):
Normal = ()
CeilRange = ()
NumberOfTiles = () |
class UnbiasedPAUCLoss(nn.Module):
def __init__(self, alpha, beta, device):
super(UnbiasedPAUCLoss, self).__init__()
self.alpha = torch.tensor(alpha)
self.na = alpha
self.beta = torch.tensor(beta)
self.kappa = torch.tensor(2)
self.a = torch.tensor(0.5).to(device)
... |
def get_hw_timming(in_dir):
for _iter in itertools.count(0, 1):
block_filename = f'iter{_iter}.profile'
block_filename = os.path.join(in_dir, block_filename)
if os.path.isfile(block_filename):
(yield BlockTimelineRecord(block_filename))
else:
break |
class Functional():
def __init__(self, target, normal):
self.target = target
self.n = normal
self.J = None
def solver_step(self, numerical_solution, coefficient):
self.J = assemble(((((coefficient * inner(self.n, grad(numerical_solution))) - self.target) ** 2) * ds)) |
class DistanceRepresentation():
def distance(self, p1s: ma.MaskedArray, p2s: ma.MaskedArray) -> ma.MaskedArray:
diff = (p1s - p2s)
square = ma.power(diff, 2)
sum_squares = square.sum(axis=(- 1))
sqrt = ma.sqrt(sum_squares).filled(0)
return sqrt
def __call__(self, p1s: ma.... |
def add_test(cls, layouts, alignments, element_output, element_accumulator, element_epilogue, cluster_shape, threadblock_shape, stages, opclass, persistent=False):
def run(self):
element_A = cutlass.int8
element_B = cutlass.int8
inst_shape = ([1, 1, 1] if (opclass == cutlass.OpClass.Simt) el... |
_dispatch
def irfft2(x, s=None, axes=((- 2), (- 1)), norm=None, overwrite_x=False, workers=None, *, plan=None):
return (Dispatchable(x, np.ndarray),) |
def load_test_data(query_andwer_file, collections_file):
questions = []
answers = []
for line in open(query_andwer_file, encoding='utf-8'):
line = line.strip().split('\t')
questions.append(line[0])
answers.append(eval(line[1]))
collections = {}
for line in open(collections_fi... |
class Bottleneck(nn.Module):
expansion: int = 4
def __init__(self, inplanes: int, planes: int, stride: int=1, downsample: Optional[nn.Module]=None, groups: int=1, base_width: int=64, dilation: int=1, norm_layer: Optional[Callable[(..., nn.Module)]]=None, outdim: int=0) -> None:
super(Bottleneck, self)._... |
def qmu_tilde(mu, data, pdf, init_pars, par_bounds, fixed_params, return_fitted_pars=False):
if (pdf.config.poi_index is None):
raise UnspecifiedPOI('No POI is defined. A POI is required for profile likelihood based test statistics.')
if (par_bounds[pdf.config.poi_index][0] != 0):
log.warning(((... |
def generate_layer(global_info, writer, out_file, tiu_instance_map, gdma_instance_map, chip_arch):
layer_list = []
for sub_net in global_info.subnet_list:
if (sub_net is not None):
layer_list.extend(sub_net.layer_list)
layer_infos = TotalLayerInfo(writer, layer_list)
layer_infos.add_... |
class SqlTemplate():
def sanitizeSql(sql):
s = sql.strip().lower()
if (not (s[(- 1)] == ';')):
s += ';'
s = re.sub('\\(', ' ( ', s)
s = re.sub('\\)', ' ) ', s)
words = ['index', 'table', 'day', 'year', 'user', 'text']
for word in words:
s = re.... |
def make_data_loader(opt, *args):
if (opt.dataset == 'atomic'):
return atomic_data.GenerationDataLoader(opt, *args)
elif (opt.dataset == 'conceptnet'):
return conceptnet_data.GenerationDataLoader(opt, *args) |
def test_methods_and_attributes():
instance1 = m.ExampleMandA()
instance2 = m.ExampleMandA(32)
instance1.add1(instance2)
instance1.add2(instance2)
instance1.add3(instance2)
instance1.add4(instance2)
instance1.add5(instance2)
instance1.add6(32)
instance1.add7(32)
instance1.add8(32... |
def test_load_svmlight_files():
data_path = _svmlight_local_test_file_path(datafile)
(X_train, y_train, X_test, y_test) = load_svmlight_files(([str(data_path)] * 2), dtype=np.float32)
assert_array_equal(X_train.toarray(), X_test.toarray())
assert_array_almost_equal(y_train, y_test)
assert (X_train.d... |
def load_toxcast(featurizer='Weave', cross_validation=False, test=False, split='random', reload=True, K=5, mode='regression', predict_cold=False, cold_drug=False, cold_target=False, cold_drug_cluster=False, split_warm=False, filter_threshold=0, prot_seq_dict=None, currdir='./', oversampled=False, input_protein=True, re... |
class Codegen():
def __init__(self, inputs: Values, outputs: Values, config: codegen_config.CodegenConfig, name: T.Optional[str]=None, return_key: T.Optional[str]=None, sparse_matrices: T.Sequence[str]=None, docstring: str=None) -> None:
if (sf.epsilon() == 0):
warning_message = '\n ... |
def load_url(url, model_dir=None, map_location=None, progress=True):
if (model_dir is None):
torch_home = os.path.expanduser(os.getenv('TORCH_HOME', '~/.torch'))
model_dir = os.getenv('TORCH_MODEL_ZOO', os.path.join(torch_home, 'models'))
if (not os.path.exists(model_dir)):
os.makedirs(m... |
class CPPTestItem(pytest.Item):
def __init__(self, *, binary, test, script=None, args=None, **kwargs):
super().__init__(**kwargs)
self.binary = binary
self.test = test
self.script = script
self.args = args
def runtest(self):
import taichi as ti
ti_lib_dir ... |
class SawyerPegUnplugSideV2Policy(Policy):
_fully_parsed
def _parse_obs(obs):
return {'hand_pos': obs[:3], 'peg_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[... |
def main():
parser = argparse.ArgumentParser(description='FixMatch Training')
parser.add_argument('--root', default='./data', type=str, help='dataset directory')
parser.add_argument('--wresnet-k', default=2, type=int, help='width factor of wide resnet')
parser.add_argument('--wresnet-n', default=28, typ... |
def main_worker(gpu, ngpus_per_node, args):
args.gpu = gpu
if (args.multiprocessing_distributed and (args.gpu != 0)):
def print_pass(*args):
pass
builtins.print = print_pass
if (args.gpu is not None):
print('Use GPU: {} for training'.format(args.gpu))
if args.distribu... |
class Inception3(nn.Module):
def __init__(self, num_classes=1000, aux_logits=True, transform_input=False):
super(Inception3, self).__init__()
self.aux_logits = aux_logits
self.transform_input = transform_input
self.Conv2d_1a_3x3 = BasicConv2d(3, 32, kernel_size=3, stride=2)
s... |
class CartanType_affine(CartanType, cartan_type.CartanType_affine):
def classical(self):
return self.dual().classical().dual()
def basic_untwisted(self):
from . import cartan_type
if (self.dual().type() == 'B'):
return cartan_type.CartanType(['A', ((self.classical().rank() * ... |
def dtype_to_cudadatatype(dtype: dtypes.typeclass) -> str:
types = {dtypes.float16: 'CUDA_R_16F', dtypes.float32: 'CUDA_R_32F', dtypes.complex64: 'CUDA_C_32F', dtypes.float64: 'CUDA_R_64F', dtypes.complex128: 'CUDA_C_64F', dtypes.int8: 'CUDA_R_8I', dtypes.uint8: 'CUDA_R_8U', dtypes.int32: 'CUDA_R_32I'}
return t... |
_spec_function('truthful_qa')
def get_truthful_qa_spec(task: str, method: str=ADAPT_MULTIPLE_CHOICE_JOINT) -> RunSpec:
scenario_spec = ScenarioSpec(class_name='helm.benchmark.scenarios.truthful_qa_scenario.TruthfulQAScenario', args={'task': task})
adapter_spec = get_multiple_choice_adapter_spec(method=method, i... |
_processor('frcnn_preprocess')
class FRCNNPreprocess(BaseProcessor):
class FRCNNPreprocessConfig():
model: omegaconf.DictConfig = omegaconf.MISSING
input: omegaconf.DictConfig = omegaconf.MISSING
size_divisibility: int = 0
pad_value: float = 0
def __init__(self, config: FRCNNPrep... |
class StanfordModel():
def __init__(self, model):
self.model = model
def tokenize(self, text, a, b, pronoun_offset, a_offset, b_offset, **kwargs):
res = self.model.api_call(text, properties={'annotators': 'tokenize,ssplit'})
res = AttrDict(res)
sent_lens = ([0] + [len(sent.tokens... |
class SliceCombinerTest(unittest.TestCase):
def setUpClass(cls):
random.seed(123)
np.random.seed(123)
torch.manual_seed(123)
def test_forward_shape(self):
batch_size = 4
h_dim = 20
num_classes = 2
outputs = {'task_slice:base_ind_head': torch.FloatTensor(ba... |
.parametrize('a00', [float(i) for i in range(10)])
_utils.test(require=ti.extension.data64, default_fp=ti.f64, fast_math=False)
def test_solve_3x3_f64(a00):
_test_solve_3x3(ti.f64, a00) |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-n', '--n', type=int, required=True)
parser.add_argument('--toy_example_name', choices=['random_projections', 'no_projections'], required=True)
parser.add_argument('--p_correlation', type=float)
parser.add_argument('--mean_causal', ... |
_task('multilingual_translation_latent_depth')
class MultilingualTranslationTaskLatentDepth(MultilingualTranslationTask):
def add_args(parser):
MultilingualTranslationTask.add_args(parser)
parser.add_argument('--encoder-latent-layer', action='store_true', help='latent layer selection in encoder')
... |
def find_optimizer_using_name(optimizer_name):
optimizer_filename = (('optimizers.' + optimizer_name) + '_optimizer')
optimizerlib = importlib.import_module(optimizer_filename)
optimizer = None
target_optimizer_name = (optimizer_name.replace('_', '') + 'optimizer')
for (name, cls) in optimizerlib.__... |
def test_straight_waveguide_power_poynting():
space = Simspace(TESTDATA, optplan.SimulationSpace(pml_thickness=[10, 10, 10, 10, 0, 0], mesh=optplan.UniformMesh(dx=40), sim_region=optplan.Box3d(center=[0, 0, 0], extents=[5000, 5000, 40]), eps_bg=optplan.GdsEps(gds='straight_waveguide.gds', mat_stack=optplan.GdsMater... |
class WnliProcessor(DataProcessor):
def get_train_examples(self, data_dir):
return self._create_examples(self._read_tsv(os.path.join(data_dir, 'train.tsv')), 'train')
def get_dev_examples(self, data_dir):
return self._create_examples(self._read_tsv(os.path.join(data_dir, 'dev.tsv')), 'dev')
... |
def test_vector_equivariance():
torch.manual_seed(1234)
rotate = torch.tensor([[0.9886788, (- 0.110237), 0.1017945], [0.136363, 0.9431761, (- 0.3030248)], [(- 0.0626055), 0.3134752, 0.9475304]])
model = create_model(load_example_args('equivariant-transformer', prior_model=None, output_model='VectorOutput'))... |
class ManinMap():
def __init__(self, codomain, manin_relations, defining_data, check=True):
self._codomain = codomain
self._manin = manin_relations
if check:
if (coercion_model.get_action(codomain, Sigma0(manin_relations._N)) is None):
raise ValueError('Codomain m... |
class TFCvtSelfAttention(tf.keras.layers.Layer):
def __init__(self, config: CvtConfig, num_heads: int, embed_dim: int, kernel_size: int, stride_q: int, stride_kv: int, padding_q: int, padding_kv: int, qkv_projection_method: str, qkv_bias: bool, attention_drop_rate: float, with_cls_token: bool=True, **kwargs):
... |
def sgx_stats_pid(pid: int) -> dict:
fmt = ''.join((x['type'] for x in _sgx_enclave_usage))
buffer = struct.pack(fmt, *((pid if (x['name'] == 'sgx_pid') else x['default_value']) for x in _sgx_enclave_usage))
try:
with open('/dev/isgx', 'r+b', buffering=0) as isgx:
result = struct.unpack(... |
class TStopwatch(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
LoadTables = _snap.TStopwatch_LoadTables
Preprocess ... |
class TaskOutputList(object):
def __init__(self, outputs=None):
self.outputs = (outputs or [])
def names(self):
names = []
for o in self.outputs:
names += o.names
return names
def set_values(self, values, _fetch_func=None):
offset = 0
for o in self... |
def create(args):
dataset = args.dataset.split('-')[0]
dataset_args = args.dataset_args[dataset]
if (dataset not in __generator.keys()):
logging.info('')
logging.error('Error: Do NOT exist this dataset: {}!'.format(args.dataset))
raise ValueError()
return __generator[dataset](arg... |
class TestUtilityOps(serial.SerializedTestCase):
(X=hu.tensor(), args=st.booleans(), **hu.gcs)
(deadline=10000)
def test_slice(self, X, args, gc, dc):
X = X.astype(dtype=np.float32)
dim = random.randint(0, (X.ndim - 1))
slice_start = random.randint(0, (X.shape[dim] - 1))
slic... |
class TFEsmForSequenceClassification(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
def show_all():
(fig, ax) = plt.subplots(2, 2, gridspec_kw={'width_ratios': [1, 1], 'height_ratios': [1, 1]})
dataset = 0
result = [RESULT[dataset] for RESULT in RESULTS]
Y = [(num - result[0]) for num in result][1:]
ax[0][0].bar(X, Y, color=color)
ax[0][0].set_xticklabels(X, fontsize=18)
ax... |
class CsBbox(CsObject):
def __init__(self):
CsObject.__init__(self, CsObjectType.BBOX)
self.bbox = []
self.bboxVis = []
self.instanceId = (- 1)
def __str__(self):
bboxText = ''
bboxText += '[(x1: {}, y1: {}), (w: {}, h: {})]'.format(self.bbox[0], self.bbox[1], sel... |
class DirectedGraphSAGELinkGenerator(BatchedLinkGenerator):
def __init__(self, G, batch_size, in_samples, out_samples, seed=None, name=None, weighted=False):
super().__init__(G, batch_size)
self.in_samples = in_samples
self.out_samples = out_samples
self._name = name
self.wei... |
def smis_to_actions(char_dict, smis):
max_seq_length = (char_dict.max_smi_len + 1)
enc_smis = list(map((lambda smi: (char_dict.encode(smi) + char_dict.END)), smis))
actions = np.zeros((len(smis), max_seq_length), dtype=np.int32)
seq_lengths = np.zeros((len(smis),), dtype=np.long)
for (i, enc_smi) in... |
def test():
one = ak.with_parameter([1, 2, [], [3, 4]], 'one', 'one')
two = ak.with_parameter([100, 200, 300], 'two', 'two')
three = ak.with_parameter([{'x': 1}, {'x': 2}, 5, 6, 7], 'two', 'two')
result = ak.concatenate((two, one, three))
assert (ak.parameters(result) == {}) |
def set_seed(seed=None):
if (seed is None):
seed = random.randint(1, 10000)
random.seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
return seed |
class BatchIncrementalClassifier(BaseSKMObject, ClassifierMixin, MetaEstimatorMixin):
def __init__(self, base_estimator=DecisionTreeClassifier(), window_size=100, n_estimators=100):
self.window_size = window_size
self.n_estimators = n_estimators
self.base_estimator = base_estimator
s... |
class MCTCTForCTC(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def GenerateSM70_WmmaTensorOp_161616(manifest, cuda_version):
layouts = [(LayoutType.ColumnMajor, LayoutType.ColumnMajor, LayoutType.ColumnMajor), (LayoutType.ColumnMajor, LayoutType.RowMajor, LayoutType.ColumnMajor), (LayoutType.RowMajor, LayoutType.ColumnMajor, LayoutType.ColumnMajor), (LayoutType.RowMajor, Layou... |
def get_mongo_config(config_path):
with open(config_path, 'r') as conf:
config = yaml.load(conf)
return (config['db_host'], config['db_port']) |
def group_parameters_for_optimizer(model, optimizer_cfg, bias_weight_decay=False, normalization_weight_decay=False):
if ('weight_decay' in optimizer_cfg):
weight_decay = optimizer_cfg.weight_decay
else:
signature = inspect.signature(hydra.utils.get_class(optimizer_cfg._target_))
if ('wei... |
def __get_format_len(f):
if isinstance(f, GDMAFormat):
if (f == GDMAFormat.FLOAT32):
return 4
elif ((f == GDMAFormat.INT16) or (f == GDMAFormat.FLOAT16)):
return 2
else:
return 1
elif ((f == BDFormat.FP32) or (f == BDFormat.INT32)):
return 4
... |
def apportion(v, default_ancestor, distance):
w = v.lbrother()
if (w is not None):
vir = vor = v
vil = w
vol = v.lmost_sibling
sir = sor = v.mod
sil = vil.mod
sol = vol.mod
while (vil.right() and vir.left()):
vil = vil.right()
vir =... |
def update_config(cfg_old, cfg_new):
for (k, v) in cfg_new.items():
if (k in cfg_old.__dict__):
setattr(cfg_old, k, v)
return cfg_old |
class MultiScaleCornerCrop(object):
def __init__(self, scales, size, interpolation=Image.BILINEAR):
self.scales = scales
self.size = size
self.interpolation = interpolation
self.crop_positions = ['c', 'tl', 'tr', 'bl', 'br']
def __call__(self, img, inv, flow):
min_length ... |
def max(x, axis=None, keepdims=False):
axis = _normalize_axis(axis, get_ndim(x))
return tf.reduce_max(x, axis=axis, keep_dims=keepdims) |
def jit_type_of(arg):
jit_type = arg.get('jit_type')
if (not jit_type):
jit_type = TYPE_MAP[arg['simple_type']]
if is_sized_intlist_arg(arg):
jit_type = 'int[{}]'.format(arg['size'])
jit_type = optional_type_of(arg, jit_type)
jit_type = annotated_type_of(arg, jit_type... |
class PerceiverForSequenceClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class sDMA_masked_select__reg(atomic_reg):
OP_NAME = 'sDMA_masked_select '
_fields_ = [('intr_en', ctypes.c_uint64, 1), ('stride_enable', ctypes.c_uint64, 1), ('nchw_copy', ctypes.c_uint64, 1), ('cmd_short', ctypes.c_uint64, 1), ('decompress_enable', ctypes.c_uint64, 1), ('cmd_id_en', ctypes.c_uint64, 4), ('cmd... |
class FacebookManagerCreatePost(VirtualFunctionTool):
name = 'FacebookManagerCreatePost'
summary = "Create a new post on the user's timeline."
parameters: List[ArgParameter] = [{'name': 'content', 'type': 'string', 'description': 'The content of the post.', 'required': True}, {'name': 'media_path', 'type': ... |
def test_ListOffset_append():
def f15(builder):
content = builder.begin_list()
content.append(1.1)
content.append(2.2)
content.append(3.3)
builder.end_list()
builder.begin_list()
builder.end_list()
builder.begin_list()
content.append(4.4)
... |
def load_student_model(checkpoint_path, model):
def clean_state_dict(state):
for k in list(ckpt.keys()):
if ('model' in k):
ckpt[k.replace('student_model.', '')] = ckpt[k]
del ckpt[k]
return state
ckpt = torch.load(checkpoint_path, map_location=torch.devic... |
class MsraNERPipe(_CNNERPipe):
def process_from_file(self, paths=None) -> DataBundle:
data_bundle = MsraNERLoader().load(paths)
return self.process(data_bundle) |
class _WorkspaceCtx(object):
def __init__(self, workspace_id):
self.workspace_id = workspace_id
self.workspace_stack = []
def __enter__(self):
self.workspace_stack.append(workspace.CurrentWorkspace())
workspace.SwitchWorkspace(self.workspace_id, create_if_missing=True)
def __... |
def test_read_sentences():
with tempfile.TemporaryDirectory() as tempdir:
raw_filename = os.path.join(tempdir, 'raw.tsv')
with open(raw_filename, 'w') as fout:
fout.write(FBK_SAMPLE)
sentences = split_wikiner.read_sentences(raw_filename, 'utf-8')
assert (len(sentences) ==... |
class TrackingRenderer():
def __init__(self, save_path):
self.save_path = save_path
self.id2color = {}
def render(self, events: DataFrame, timestamp: int, frame_gt: List[TrackingBox], frame_pred: List[TrackingBox]) -> None:
print('Rendering {}'.format(timestamp))
switches = event... |
(Output('the-toronto-star-graph', 'figure'), Input('stored-df-data', 'data'), prevent_initial_call=True)
def update_fig_7(jsonified_cleaned_data):
df = pd.read_json(jsonified_cleaned_data, orient='split')
return plot_lines(df, 'The Star') |
def parse_dbpedia_entities(path='./predicates.txt'):
with open(path, 'r') as infile, open('predicates_labels.txt', 'w') as out:
for line in infile:
entity_uri = ';'.join(line.split(';')[:(- 1)])
entity_label = entity_uri.strip('/').split('/')[(- 1)].strip('>').lower()
out... |
class SubsetImageIDs():
def __init__(self, config):
super().__init__()
self.data_dir = config.data_dir
self.save_data_dir = config.save_data_dir
self.all_image_ids = []
def extract_image_ids(self):
for data_type in ['train', 'val', 'test']:
data_list = self._g... |
class OracleTeacher():
def __init__(self, mins, maxs, window_step_vector, seed=None, reward_thr=230, step_rate=50):
self.seed = seed
if (not seed):
self.seed = np.random.randint(42, 424242)
np.random.seed(self.seed)
self.mins = np.array(mins, dtype=np.float32)
sel... |
class PGGenerator(nn.Module):
def __init__(self, resolution, latent_size, final_channel=3, fmap_base=(2 ** 13), fmap_decay=1.0, fmap_max=(2 ** 9), is_tanh=False):
super(PGGenerator, self).__init__()
self.latent_size_ = latent_size
self.is_tanh_ = is_tanh
self.final_channel_ = final_c... |
_lr_scheduler('fixed')
class FixedSchedule(FairseqLRScheduler):
def __init__(self, args, optimizer):
super().__init__(args, optimizer)
args.warmup_updates = (getattr(args, 'warmup_updates', 0) or 0)
self.lr = args.lr[0]
if (args.warmup_updates > 0):
self.warmup_factor = (... |
def get_non_error_tasks(sessions):
tasks = []
for sess in sessions:
if (not sess['error']):
task = (sess['question'], sess['answer'])
tasks.append(task)
tasks = list(set(tasks))
return tasks |
def silhouette(data, labels, precomp_dict, metric='sqeuclidean'):
if (f'dists_{metric}' in precomp_dict):
return silhouette_score(precomp_dict[f'dists_{metric}'], labels, metric='precomputed')
else:
return silhouette_score(data, labels, metric=metric) |
class Registry():
task_name_mapping: Dict[(str, TAPETaskSpec)] = {}
metric_name_mapping: Dict[(str, Callable)] = {}
def register_task(cls, task_name: str, num_labels: int=(- 1), dataset: Optional[Type[Dataset]]=None, models: Optional[Dict[(str, Type[ProteinModel])]]=None):
if (dataset is not None):
... |
_cache(maxsize=100000)
def rgamma_cached(x, dps):
with mp.workdps(dps):
return mp.rgamma(x) |
_tf
class TFGenerationIntegrationTests(unittest.TestCase, GenerationIntegrationTestsMixin):
if is_tf_available():
framework_dependent_parameters = {'AutoModelForCausalLM': TFAutoModelForCausalLM, 'AutoModelForSpeechSeq2Seq': TFAutoModelForSpeechSeq2Seq, 'AutoModelForSeq2SeqLM': TFAutoModelForSeq2SeqLM, 'Aut... |
def process_in_chunks(function, *args, batch_size, out=None, **kwargs):
total_size = args[0].shape[0]
first_output = function(*[x[0:batch_size] for x in args])
output_shape = ((total_size,) + tuple(first_output.shape[1:]))
if (out is None):
out = torch.zeros(*output_shape, dtype=first_output.dty... |
class UsageStatsStatus(Enum):
ENABLED_EXPLICITLY = auto()
DISABLED_EXPLICITLY = auto()
ENABLED_BY_DEFAULT = auto() |
def add_preprocess_args(parser):
group = parser.add_argument_group('Preprocessing')
group.add_argument('-s', '--source-lang', default=None, metavar='SRC', help='source language')
group.add_argument('-t', '--target-lang', default=None, metavar='TARGET', help='target language')
group.add_argument('--train... |
class CharDecoder(Decoder):
def decode(self, trg_sentence):
return ''.join((trg_wmap.get(c, '<UNK>') for c in trg_sentence)).replace('_', ' ') |
def homogeneous_symmetric_function(j, x):
from sage.combinat.integer_vector import IntegerVectors
from sage.misc.misc_c import prod
return sum((prod(((xx ** pp) for (xx, pp) in zip(x, p))) for p in IntegerVectors(j, length=len(x)))) |
def datetimes_to_dataset(times, dst_file):
days = [[times[0]]]
current_day = days[0]
for t in times[1:]:
if (t.date() != current_day[0].date()):
current_day = []
days.append(current_day)
if ((len(current_day) > 0) and (t == current_day[(- 1)])):
continue
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.