code stringlengths 101 5.91M |
|---|
def idctn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
type = _inverse_typemap[type]
shape = _good_shape(x, shape, axes)
return _pocketfft.dctn(x, type, shape, axes, norm, overwrite_x) |
class TestRegistrable(TestCase):
def test_should_register_subclass(self):
class MyBaseClass(Registrable):
pass
('first_subclass')
class MyFirstSubclass(MyBaseClass):
pass
('second_subclass')
class MySecondSubclass(MyBaseClass):
pass
... |
def load(file, file_format=None, file_client_args=None, **kwargs):
if isinstance(file, Path):
file = str(file)
if ((file_format is None) and is_str(file)):
file_format = file.split('.')[(- 1)]
if (file_format not in file_handlers):
raise TypeError(f'Unsupported format: {file_format}'... |
class MBartTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
model_input_names = ['input_ids', 'attention_mask']
prefix_tokens: List[int] = []
suffix_tokens:... |
class REDSDataset(data.Dataset):
def __init__(self, opt):
super(REDSDataset, self).__init__()
self.opt = opt
(self.gt_root, self.lq_root) = (Path(opt['dataroot_gt']), Path(opt['dataroot_lq']))
self.flow_root = (Path(opt['dataroot_flow']) if (opt['dataroot_flow'] is not None) else Non... |
class OpenImagesSegChallenge2019Cfg(OpenImagesSegCfg):
num_classes: int = 300
ann_class_map: str = 'annotations/challenge-2019/challenge-2019-classes-description-segmentable.csv'
splits: Dict[(str, dict)] = field(default_factory=(lambda : dict(train=dict(), val=dict(), test=dict()))) |
def equalize(image, factor):
image = Image.fromarray(image)
image = ImageOps.equalize(image)
return np.asarray(image) |
def record_repetitive_adjacent(graph, node_weight_function, rtol=0.002, do_topo_sort=True):
if do_topo_sort:
graph.topo_sort(change_graph=False)
topo_sorted_nodes_to_weight = SortedDict({n.topo_sort_id: node_weight_function(n) for n in graph.non_input_nodes})
found_sets = []
cur = None
rsum ... |
def handleTimer():
global timer
print('publishing my url')
timer = threading.Timer(5, handleTimer)
timer.start() |
def get_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--run-type', choices=['train', 'eval'], required=True, help='run type of the experiment (train or eval)')
parser.add_argument('--exp-config', type=str, required=True, help='path to config yaml containing info about experiment')
pa... |
def create_py_map(sdfg):
py_mapper = MapPython(sdfg.name)
made_with_api = py_mapper.mapper(sdfg)
folder = sdfg.build_folder
save('py', sdfg.name, py_mapper.map, folder)
sourceFiles = get_src_files(sdfg)
return (folder, sourceFiles, made_with_api) |
def get_sampling(im):
if ((not hasattr(im, 'layers')) or (im.layers in (1, 4))):
return (- 1)
sampling = ((im.layer[0][1:3] + im.layer[1][1:3]) + im.layer[2][1:3])
return samplings.get(sampling, (- 1)) |
def _cuda(self, device=None, non_blocking=False, **kwargs):
non_blocking = _get_async_or_non_blocking('cuda', non_blocking, kwargs)
if self.is_cuda:
if (device is None):
device = torch.cuda.current_device()
if (self.get_device() == device):
return self
elif (device is... |
('span_annotation')
class SpanAnnotationReader(DatasetReader):
def __init__(self, max_span_width: int, token_indexers: Dict[(str, TokenIndexer)]=None) -> None:
self.max_span_width = max_span_width
self._token_indexers = (token_indexers or {'tokens': SingleIdTokenIndexer()})
self._tag_widths:... |
class Cache(object):
def __init__(self, base):
if (not os.path.isdir(base)):
os.makedirs(base)
if ((os.stat(base).st_mode & 63) != 0):
logger.warning("Directory '%s' is not private", base)
self.base = os.path.abspath(os.path.normpath(base))
def prefix_to_dir(self,... |
def adjust_learning_rate_D(optimizer, i_iter):
lr = lr_poly(args.learning_rate_D, i_iter, args.num_steps, args.power)
optimizer.param_groups[0]['lr'] = lr
if (len(optimizer.param_groups) > 1):
optimizer.param_groups[1]['lr'] = (lr * 10) |
def from_fraction_field(L, x):
d = L(x.denominator())
if d.is_unit():
n = L(x.numerator())
return (n * d.inverse_of_unit())
else:
raise TypeError('fraction must have unit denominator') |
class MisGANImputationSampler(BaseImputationSampler):
def __init__(self, data_loader, imputer, batch_size=256):
super().__init__(data_loader)
self.imputer = imputer
self.impu_noise = torch.FloatTensor(batch_size, 3, 64, 64).to(device)
def impute(self, data, mask):
if (data.shape[... |
def invweibull_pdf(x, c):
if (x > 0):
return (c * math.exp((((- (c + 1)) * math.log(x)) - (x ** (- c)))))
return 0.0 |
class I1Pool(nn.Module):
def forward(self, x, guide):
x = x.contiguous()
guide = guide.expand_as(x).contiguous()
return I1PoolFunction.apply(x, guide) |
class RAM():
def __init__(self, ignore_warnings=False):
self._consumption = 0
self._ignore_warnings = ignore_warnings
self._start = time.time()
def get_consumption(self):
self.calculate_consumption()
return self._consumption
def _get_memory_used(self):
current... |
def make_dir(filename):
folder = os.path.dirname(filename)
if (not os.path.exists(folder)):
os.makedirs(folder) |
def _get_lvis_instances_meta_v0_5():
assert (len(LVIS_V0_5_CATEGORIES) == 1230)
cat_ids = [k['id'] for k in LVIS_V0_5_CATEGORIES]
assert ((min(cat_ids) == 1) and (max(cat_ids) == len(cat_ids))), 'Category ids are not in [1, #categories], as expected'
lvis_categories = sorted(LVIS_V0_5_CATEGORIES, key=(l... |
.parametrize('version', ['1.0.0'])
.parametrize('schema', ['defs.json', 'measurement.json', 'model.json', 'workspace.json'])
def test_get_schema(version, schema):
assert pyhf.schema.load_schema(f'{version}/{schema}') |
class ConcatPoincareLayer(nn.Module):
def __init__(self, d1, d2, d_out, c):
super(ConcatPoincareLayer, self).__init__()
self.d1 = d1
self.d2 = d2
self.d_out = d_out
self.l1 = HypLinear(d1, d_out, bias=False, c=c)
self.l2 = HypLinear(d2, d_out, bias=False, c=c)
... |
def hide_available_pandas(monkeypatch):
import_orig = builtins.__import__
def mocked_import(name, *args, **kwargs):
if (name == 'pandas'):
raise ImportError()
return import_orig(name, *args, **kwargs)
monkeypatch.setattr(builtins, '__import__', mocked_import) |
def test_data_frame_ListOffsetArray_NumpyArray():
array = ak.contents.listoffsetarray.ListOffsetArray(ak.index.Index(np.array([1, 4, 4, 6, 7], np.int64)), ak.contents.numpyarray.NumpyArray(np.array([6.6, 1.1, 2.2, 3.3, 4.4, 5.5, 7.7])))
layout = array
generator = ak._connect.cling.togenerator(layout.form, f... |
class UnpairedAudioTextConfig(FairseqDataclass):
data: str = field(default=MISSING, metadata={'help': 'path to data directory containing audio'})
text_data: str = field(default=MISSING, metadata={'help': 'path to data directory containing text'})
max_length: Optional[int] = None
labels: Optional[str] = ... |
def _get_step_context(step):
proto = step.Proto()
if proto.should_stop_blob:
return (call('loop'), False)
if (proto.num_iter and (proto.num_iter != 1)):
return (call('loop', [proto.num_iter]), False)
if (proto.num_concurrent_instances > 1):
return (call('parallel', [('num_instanc... |
class CiscoUmbrellaGetLogDetails(VirtualFunctionTool):
name = 'CiscoUmbrellaGetLogDetails'
summary = 'Get detailed information about a specific security log.'
parameters: List[ArgParameter] = [{'name': 'log_id', 'type': 'string', 'description': 'The unique identifier of the log.', 'required': True}]
ret... |
def get_attr(model: torch.jit.RecursiveScriptModule, node: torch.Node):
if (node.kind() == 'prim::Param'):
return (model, '')
if (node.kind() == 'prim::GetAttr'):
name = node.s('name')
(obj, parent) = get_attr(model, node.input().node())
return (getattr(obj, name), (((parent + '.... |
def CalculateMoranAutoMutability(ProteinSequence):
result = CalculateEachMoranAuto(ProteinSequence, _Mutability, '_Mutability')
return result |
def quaternion_linear_rotation_op(input, r_weight, i_weight, j_weight, k_weight, bias, scale, zero_kernel):
square_r = (r_weight * r_weight)
square_i = (i_weight * i_weight)
square_j = (j_weight * j_weight)
square_k = (k_weight * k_weight)
norm = (torch.sqrt((((square_r + square_i) + square_j) + squ... |
def compute_temporal_iou(pred, gt):
intersection = max(0, (min(pred[1], gt[1]) - max(pred[0], gt[0])))
union = (max(pred[1], gt[1]) - min(pred[0], gt[0]))
if (union == 0):
return 0
else:
return ((1.0 * intersection) / union) |
def register_Ns3MmWaveMacPduHeader_methods(root_module, cls):
cls.add_constructor([param('ns3::MmWaveMacPduHeader const &', 'arg0')])
cls.add_constructor([])
cls.add_constructor([param('uint16_t', 'frameNo'), param('uint8_t', 'sfNo'), param('uint8_t', 'slotNo')])
cls.add_method('AddSubheader', 'void', [... |
class Dataset():
def __init__(self, name, t0, t1, dt, precision, obs_func=None):
self.dataset = BasicDataset(name, t0, t1, dt, precision)
self.obs_func = obs_func
def write(self, func, t, name):
self.dataset.write(func, t, name=name)
def read(self, func, t, name='v'):
if (sel... |
def register_Ns3Ipv6Prefix_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
cls.add_constructor([])
cls.add_constructor([param('uint8_t *', 'prefix')])
cls.add_constructor([param('char const *', 'prefix'... |
class RAND_reg(atomic_reg):
OP_NAME = 'RAND'
_fields_ = [('cmd_short', ctypes.c_uint64, 1), ('op_code', ctypes.c_uint64, 16), ('cmd_id_dep', ctypes.c_uint64, 23), ('dbg_mode', ctypes.c_uint64, 1), ('tsk_typ', ctypes.c_uint64, 4), ('tsk_eu_typ', ctypes.c_uint64, 5), ('opt_rq', ctypes.c_uint64, 1), ('tsk_opd_num'... |
class V2VModel(nn.Module):
def __init__(self, input_channels, output_channels):
super().__init__()
self.encoder_decoder = EncoderDecoder(in_dim=input_channels)
self.output_layer = nn.Conv2d(128, output_channels, kernel_size=1, stride=1, padding=0)
self._initialize_weights()
def f... |
def main(cfg):
(dataset, train_loader, test_loader, num_query, num_classes) = make_data_loader(cfg)
model = build_model(num_classes, 'base', pretrain_choice=True)
model = (torch.nn.DataParallel(model).cuda() if torch.cuda.is_available() else model)
loss_func = make_loss()
optimizer = make_optimizer(... |
def convert_extras(extras):
if (not extras):
return set()
return Requirement(('placeholder' + extras.lower())).extras |
class FancyTuple(tuple):
def __repr__(self):
length = len(str((len(self) - 1)))
return '\n'.join(('{0:>{1}}: {2}'.format(i, length, item) for (i, item) in enumerate(self)))
def __getslice__(self, i, j):
return self.__getitem__(slice(i, j))
def __getitem__(self, x):
res = tupl... |
((not torch), 'no PyTorch')
def test_demo_torch_export_to_onnx():
out_onnx_model = _test_torch_export_to_onnx('demos/demo-torch.config')
_test_torch_onnx_inference_seq_lens_in_out(out_onnx_model) |
def get_layers(dims: Union[(int, list)], layer_types: Union[(str, BaseLayer, list)], activations: Union[(str, BaseActivation, list)], use_bias: Union[(bool, list)], normalizations: Union[(str, list)], self_embeddings: Union[(bool, list)], sample_sizes: Union[(int, list)], loss: Union[(str, BaseLoss)]) -> list:
chec... |
def dispatchCommand(command, user, args):
command = command.lower()
if (command == 'login'):
loginUser()
return
elif (command == 'retrieve_file'):
sendFile()
return
elif (command == 'list_files'):
listFiles()
return
else:
print('Invalid Command... |
class Console(RichConsole):
CRITICAL = logging.CRITICAL
FATAL = logging.FATAL
ERROR = logging.ERROR
WARNING = logging.WARNING
WARN = logging.WARN
INFO = logging.INFO
DEBUG = logging.DEBUG
NOTSET = logging.NOTSET
def __init__(self, *args, log_level: int=INFO, **kwrags):
super(... |
def save_args(args, force_overwrite=False):
os.makedirs(args.log_dir, exist_ok=(args.exist_ok or force_overwrite))
variables = vars(args).copy()
del variables['train_tasks']
del variables['val_tasks']
with open(os.path.join(args.log_dir, 'config.json'), 'wt') as f:
json.dump(variables, f, in... |
(arg_at(0, assert_vector()))
def normalized(vec, eps=0.0):
invlen = (1 / (norm(vec) + eps))
return (invlen * vec) |
class Functional():
def __init__(self, sampler):
self.sampler = sampler
self.J = 0.0
def solver_step(self, numerical_solution, t):
obs = self.sampler.get_observation(t)
if (obs is not None):
self.J += assemble((((numerical_solution - obs) ** 2) * dx)) |
def _format(val: Any, output_format: str='standard', errors: str='coarse') -> Any:
val = str(val)
result: Any = []
if (val in NULL_VALUES):
return [np.nan]
if (not validate_lt_pvm(val)):
if (errors == 'raise'):
raise ValueError(f'Unable to parse value {val}')
error_re... |
def test_set_output_names_on_inference_model():
model = tract.onnx().model_for_path('./mobilenetv2-7.onnx')
model.set_input_fact(0, 'B,3,224,224,f32')
model.analyse()
model.set_output_names(['mobilenetv20_output_pred_fwd'])
assert (str(model.output_fact(0)) == 'B,1000,1,1,F32') |
def _ntuple(n):
def parse(x):
if isinstance(x, collections.abc.Iterable):
return x
return tuple(repeat(x, n))
return parse |
class RRG(nn.Module):
def __init__(self, n_feat, n_MRB, height, width, chan_factor, bias=False, groups=1):
super(RRG, self).__init__()
modules_body = [MRB(n_feat, height, width, chan_factor, bias, groups) for _ in range(n_MRB)]
modules_body.append(nn.Conv2d(n_feat, n_feat, kernel_size=3, str... |
_arg_scope
def variable(name, shape=None, dtype=tf.float32, initializer=None, regularizer=None, trainable=True, collections=None, device='', restore=True):
collections = list((collections or []))
collections += [tf.GraphKeys.VARIABLES, MODEL_VARIABLES]
if restore:
collections.append(VARIABLES_TO_RES... |
def get_generic_df_coefficient_symbol(k1, k2, k3, k4, k5, k6, z1, z2, z3, z4):
return symbols('C_{0}\\,{1}\\,{2}\\,{3}\\,{4}\\,{5}^{6}\\,{7}\\,{8}\\,{9}'.format(k1, k2, k3, k4, k5, k6, z1, z2, z3, z4)) |
def setup():
args = parse_arguments()
config = load_yaml(args.config)
update_not_none(config, vars(args))
setup_dirs(config)
del logging.getLogger('tensorflow').handlers[0]
setup_loggers(config['log_dir'])
os.environ['CUDA_VISIBLE_DEVICES'] = config['gpu']
backup_src(config['src_dir'])
... |
_module()
class EMAHead(BaseDecodeHead):
def __init__(self, ema_channels, num_bases, num_stages, concat_input=True, momentum=0.1, **kwargs):
super(EMAHead, self).__init__(**kwargs)
self.ema_channels = ema_channels
self.num_bases = num_bases
self.num_stages = num_stages
self.c... |
class DownSample(nn.Module):
def __init__(self, in_channels, scale_factor, chan_factor=2, kernel_size=3):
super(DownSample, self).__init__()
self.scale_factor = int(np.log2(scale_factor))
modules_body = []
for i in range(self.scale_factor):
modules_body.append(Down(in_cha... |
class HFBertMatchingTrainDataset(Dataset):
def __init__(self, tokenizer: PreTrainedTokenizer, name='STS-B', max_len: int=64):
self.tokenizer = tokenizer
self.data = load_dataset('shibing624/nli_zh', name.upper(), split='train')
self.max_len = max_len
self.name = name.upper()
def ... |
def __boost_get_version_file(self, d):
if (not d):
return None
dnode = self.root.find_dir(d)
if dnode:
return dnode.find_node(BOOST_VERSION_FILE)
return None |
class LlavaMetaForCausalLM(ABC):
def get_model(self):
pass
def get_vision_tower(self):
return self.get_model().get_vision_tower()
def encode_images(self, images):
image_features = self.get_model().get_vision_tower()(images)
image_features = self.get_model().mm_projector(image... |
def model_gen():
inputs = layers.Input(shape=[4, 4, 3])
x = layers.Conv2D(2, 2, padding='same')(inputs)
x = layers.BatchNormalization()(x)
x = layers.Activation('relu')(x)
return tf.keras.models.Model(inputs=inputs, outputs=x) |
.parametrize('v_inner_boundary, v_outer_boundary', [(3350, 3650), (2900, 3750), (2900, 3850), (2900, 3900), (2950, 3750), (2950, 3850), (2950, 3900), (3050, 3750), (3050, 3850), (3050, 3900), (3150, 3750), (3150, 3850), (3150, 3900)])
def test_plasma_vboundary(config_init_trad_fname, v_inner_boundary, v_outer_boundary,... |
class DeterministicMLPRegressor(LayersPowered, Serializable):
def __init__(self, name, input_shape, output_dim, network=None, hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.tanh, output_nonlinearity=None, optimizer=None, normalize_inputs=True):
Serializable.quick_init(self, locals())
with tf.varia... |
def test_compute_ricci_curvature():
G = nx.Graph()
G.add_edges_from([(1, 2), (2, 3), (3, 4), (2, 4)])
G.add_node(5)
frc = FormanRicci(G, method='1d')
frc.compute_ricci_curvature()
frc_edges = list(nx.get_edge_attributes(frc.G, 'formanCurvature').values())
frc_nodes = list(nx.get_node_attribu... |
class UtteranceLevel(nn.Module):
def __init__(self, input_dim, output_dim, pooling='MeanPooling', activation='ReLU', pre_net=None, post_net={'select': 'FrameLevel'}, **kwargs):
super().__init__()
latest_dim = input_dim
self.pre_net = (get_downstream_model(latest_dim, latest_dim, pre_net) if ... |
def str_presenter(dumper, data):
if (len(data.splitlines()) > 1):
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
return dumper.represent_scalar('tag:yaml.org,2002:str', data) |
def iterate_multibank_interface_ids(array: dt.Array, interface_ids: Union[(int, List[Tuple[(int, int)]])]):
if is_multibank_array_with_distributed_index(array):
for (bank, id) in interface_ids:
(yield (bank, id))
else:
(yield (0, interface_ids)) |
def ensure_dir(file_path):
directory = file_path
if (not os.path.exists(directory)):
os.makedirs(directory) |
class ConvBertForMultipleChoice():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
def aps13_f(x):
if (x == 0):
return 0
y = (1 / (x ** 2))
if (y > _MAX_EXPABLE):
return 0
return (x / np.exp(y)) |
def get_hole_identities(hole_filename, duplicate_filename):
hole_data = pickle.load(open(hole_filename, 'rb'))
duplicate_files = open(duplicate_filename, 'r').readlines()
duplicate_files = [x.strip() for x in duplicate_files]
hole_identities = []
for (k, v) in hole_data.items():
if ((k not i... |
class Credential():
def __init__(self, username, password):
self.username = username
self.password = password
def __iter__(self):
(yield self.username)
(yield self.password)
def __str__(self):
return ('%(username)s:%(password)s' % vars(self)) |
class SAC(QLearningAlgoBase[(SACImpl, SACConfig)]):
def inner_create_impl(self, observation_shape: Shape, action_size: int) -> None:
policy = create_normal_policy(observation_shape, action_size, self._config.actor_encoder_factory, device=self._device)
(q_funcs, q_func_forwarder) = create_continuous_... |
class MSMT17(BaseImageDataset):
dataset_dir = 'MSMT17_V1'
def __init__(self, root='/home/haoluo/data', verbose=True, **kwargs):
super(MSMT17, self).__init__()
self.dataset_dir = osp.join(root, self.dataset_dir)
self.train_dir = osp.join(self.dataset_dir, 'train')
self.test_dir = ... |
def find_unclean_onnx_name(model: ONNXModel, name: str) -> str:
unclean_name = [n for n in model.weights if (clean_onnx_name(n) == name)]
if (len(unclean_name) != 1):
raise ValueError(f'Could not find unclean name for name {name}')
return unclean_name[0] |
def _training_config(proto):
class TrainingConfig():
pass
config = TrainingConfig()
config.max_epoch = proto.training_config.max_epoch
config.iter_per_epoch = proto.training_config.iter_per_epoch
config.save_best = proto.training_config.save_best
config.monitor_interval = (proto.training... |
def max_pool(bottom, ks, stride=1):
return L.Pooling(bottom, pool=P.Pooling.MAX, kernel_size=ks, stride=stride) |
def get_input_tensors():
height = np.random.randint(1, 10)
width = np.random.randint(1, 10)
dtype = np.float32
input_tensor = hu.arrays(dims=[height, width], dtype=dtype, elements=st.integers(min_value=0, max_value=100))
return input_tensor |
def download_dataset(dataset_tag):
print('Downloading dataset...')
if (dataset_tag == 'zero_dce'):
gdown.download(' 'Dataset_Part1.rar', quiet=False)
print('Unpacking Dataset')
subprocess.run('unrar x Dataset_Part1.rar'.split(' '))
print('Done!!!')
elif (dataset_tag == 'dark_... |
class Market(object):
def __init__(self, root):
self.images_dir = osp.join(root)
self.train_path = 'bounding_box_train'
self.gallery_path = 'bounding_box_test'
self.query_path = 'query'
(self.train, self.query, self.gallery) = ([], [], [])
(self.num_train_ids, self.nu... |
def __add_info_subprocess(available_datasets: List[str], subparsers) -> None:
parser = subparsers.add_parser('info', formatter_class=SortingHelpFormatter, help='Show info about projects, project versions, and misuses in MUBench.', description='Show info about projects, project versions, and misuses in MUBench.')
... |
def generate_nodes(node_procs, router_names, memo_size):
nodes = [{Topology.NAME: name, Topology.TYPE: RouterNetTopo.QUANTUM_ROUTER, Topology.SEED: i, RouterNetTopo.MEMO_ARRAY_SIZE: memo_size, RouterNetTopo.GROUP: node_procs[name]} for (i, name) in enumerate(router_names)]
return nodes |
def extract_sent_candidates(text_obj):
return [' '.join((word for (word, tag) in sent)) for sent in text_obj.pos_tagged] |
def _get_filenames_and_classes(dataset_dir):
images_root = os.path.join(dataset_dir, 'images')
directories = []
class_names = []
for filename in os.listdir(images_root):
path = os.path.join(images_root, filename)
if os.path.isdir(path):
directories.append(path)
cl... |
class VarmField(ArrayLikeField):
def __init__(self, *args, **kwargs):
super().__init__(*args, field_type='varm', **kwargs) |
class RequestError(PoolError):
def __init__(self, pool, url, message):
self.url = url
PoolError.__init__(self, pool, message)
def __reduce__(self):
return (self.__class__, (None, self.url, None)) |
def _train_loader_from_config(cfg, mapper, dataset_name=None, *, dataset=None, sampler=None):
if (dataset is None):
dataset = get_detection_dataset_dicts(dataset_name, filter_empty=cfg.DATALOADER.FILTER_EMPTY_ANNOTATIONS, proposal_files=(cfg.DATASETS.PROPOSAL_FILES_TRAIN if cfg.MODEL.LOAD_PROPOSALS else Non... |
def replaces_ufunc(func: Callable[(..., Tuple[str])], name: str):
Replacements._ufunc_rep[name] = func
return func |
class LinearExtensionsOfMobile(LinearExtensionsOfPoset):
def cardinality(self):
import sage.combinat.posets.d_complete as dc
if self._poset._anchor:
anchor_index = self._poset._ribbon.index(self._poset._anchor[0])
else:
anchor_index = len(self._poset._ribbon)
... |
def clean_last_char(sentences):
for n in range(len(sentences)):
if (sentences[n][0] != ''):
sentences[n][0] = sentences[n][0][:(- 1)]
sentences[n][1] = sentences[n][1][:(- 3)]
else:
del sentences[n]
return sentences |
def test_basic():
def test_basic_tf(A: datatype[(5, 5)]):
B = (A + 1)
return (B * 2)
sdfg = test_basic_tf.to_sdfg(simplify=True)
num_map_fusions = sdfg.apply_transformations(MapFusion)
assert (num_map_fusions == 1)
num_tasklet_fusions = sdfg.apply_transformations(TaskletFusion)
a... |
def main(args=None):
args = parse_args(args=args)
utils.set_random_seed(args.seed)
args = vars(args)
logger.info('Running MWT expander in {} mode'.format(args['mode']))
if (args['mode'] == 'train'):
train(args)
else:
evaluate(args) |
def main(_):
hparams_center = HParamsCenter(HParams(load_preproc=True, bert_pretrained_dir='none', max_sequence_len=64, src_infer_dir='none', tgt_infer_dir='none', timeout=5.0, use_op_type_constraint=False, ner_dump_dir='save_ner_num', debug_dec=0, num_parallels=4, dump_dir='placeholder', clear_dump_dir=False, kb_m... |
def train(opt, log):
write_data_log(f''' {opt.exp_name}
''')
print(f''' {opt.exp_name}
''')
valid_datasets = train_datasets = [lan for lan in opt.lan_list]
best_scores = []
ned_scores = []
valid_datas = []
char = dict()
opt_log = ' Options \n'
args = vars(opt)
for (k, v) in arg... |
def test_rank_selection():
selection = sel.RankSelection()
population = [MagicMock(chrom.Chromosome) for _ in range(20)]
assert (0 <= selection.get_index(population) < len(population)) |
class PickleObject():
def __init__(self, value, expression):
self.value = value
self.expression = expression
self.immutable = False
def _sage_input_(self, sib, coerced):
self.immutable = True
return self.expression |
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.projection = nn.Linear(10, 10)
def forward(self):
pass |
(st.floats(min_value=0.0, max_value=float('inf'), exclude_min=False, exclude_max=True))
def test_normalise(value):
assert (ff.normalise(value) == (value / (1.0 + value))) |
class DeepFM(BaseModel):
def __init__(self, linear_feature_columns, dnn_feature_columns, use_fm=True, dnn_hidden_units=(256, 128), l2_reg_linear=1e-05, l2_reg_embedding=1e-05, l2_reg_dnn=0, init_std=0.0001, seed=1024, dnn_dropout=0, dnn_activation='relu', dnn_use_bn=False, task='binary', device='cpu'):
supe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.