code stringlengths 101 5.91M |
|---|
def test_contextual_confusion_matrix_points(expected_point, observed_point):
expected_return = (4, 7, 3, 5)
returned = contextual_confusion_matrix(expected_point, observed_point)
np.testing.assert_array_equal(np.array(returned), np.array(expected_return)) |
.parametrize('ctx, func_name', ctxs)
.parametrize('seed', [313])
def test_exp_double_backward(seed, ctx, func_name):
from nbla_test_utils import backward_function_tester
rng = np.random.RandomState(seed)
inputs = [rng.randn(2, 3).astype(np.float32)]
backward_function_tester(rng, F.exp, inputs=inputs, fu... |
class TestDrainConfig():
def setup(self):
self.ERROR = 0.01
def test_default_drain_config(self):
params = DrainParams()
assert isinstance(params, DrainParams)
assert (params.sim_th == pytest.approx(0.4, self.ERROR))
assert (not params.extra_delimiters)
def test_assign... |
class MlpContextEncoder(CudaModule):
def __init__(self, n, k, nembed, nhid, init_range, device_id):
super(MlpContextEncoder, self).__init__(device_id)
self.cnt_enc = nn.Embedding(n, nembed)
self.val_enc = nn.Embedding(n, nembed)
self.encoder = nn.Sequential(nn.Tanh(), nn.Linear((k * ... |
class Tree(nn.Module):
def __init__(self, tree_struct, tree_modules, split=False, node_split=None, child_left=None, child_right=None, extend=False, node_extend=None, child_extension=None, cuda_on=True, breadth_first=True, soft_decision=True):
super(Tree, self).__init__()
assert (not (split and exten... |
def to_tensor(data):
if isinstance(data, torch.Tensor):
return data
elif isinstance(data, np.ndarray):
return torch.from_numpy(data)
elif (isinstance(data, Sequence) and (not mmcv.is_str(data))):
return [to_tensor(d) for d in data]
elif isinstance(data, int):
return torch... |
class BertQA():
def __init__(self, config):
self.batch_size = config['batch_size']
self.model = AutoModelForQuestionAnswering.from_pretrained(config['model_weights'])
self.tokenizer = AutoTokenizer.from_pretrained(config['model_weights'])
self.page_retrieval = (config['page_retrieval... |
def skip_combination(net, method, suffix_aggr):
if ((net == 'vgg') and ((method == 'tlEBPreluLayer') or (method == 'tlEBPposReflect') or (method == 'tlEBPnegReflect') or (method == 'meanEBP_VGG'))):
return True
return False |
def cal_mask_bbox(head_mask, factor=1.3):
(bs, _, height, width) = head_mask.shape
bbox = np.zeros((bs, 4), dtype=np.int32)
valid = np.ones((bs,), dtype=np.float32)
for i in range(bs):
mask = head_mask[(i, 0)]
(ys, xs) = np.where((mask == 1))
if (len(ys) == 0):
valid[... |
def ID2arch(hist_df, state_str_to_state_shortname):
id2arch = {}
num_layers = sum([1 for x in hist_df.columns.values if x.startswith('L')])
for i in hist_df.ID:
arch = tuple((state_str_to_state_shortname[x][hist_df.loc[(hist_df.ID == i)][('L%i' % (x + 1))].iloc[0]] for x in range(num_layers)))
... |
def test_clean_inplace(df_urls: pd.DataFrame) -> None:
df_clean = clean_url(df_urls, column='messy_url', inplace=True, report=False)
df_check = pd.DataFrame({'messy_url_details': [np.nan, {'scheme': ' 'host': 'www.facebookee.com', 'messy_url_clean': ' 'queries': {'auth': 'facebookeeauth', 'token': 'iwusdkc', 'n... |
class MlpHead(nn.Module):
def __init__(self, dim, num_classes=1000, mlp_ratio=4, act_layer=SquaredReLU, norm_layer=nn.LayerNorm, head_dropout=0.0, bias=True):
super().__init__()
hidden_features = int((mlp_ratio * dim))
self.fc1 = nn.Linear(dim, hidden_features, bias=bias)
self.act = ... |
class PTBTokenizer():
def tokenize(self, captions_for_image):
cmd = ['java', '-cp', STANFORD_CORENLP_3_4_1_JAR, 'edu.stanford.nlp.process.PTBTokenizer', '-preserveLines', '-lowerCase']
final_tokenized_captions_for_image = {}
image_id = [k for (k, v) in captions_for_image.items() for _ in ran... |
def import_dataset(name='CORA'):
root = f'BENCHMARK/{name.upper()}/'
if (name.upper() == 'CORA'):
dataset = Planetoid(root=root, name='CORA')
elif (name.upper() == 'CORA-F'):
dataset = CitationFull(root=root, name='cora')
elif (name.upper() == 'CITESEER'):
dataset = Planetoid(roo... |
def alpha_analysis(alpha):
try:
if (alpha < 0.667):
return 'Low'
if (0.667 <= alpha < 0.8):
return 'Tentative'
if (alpha >= 0.8):
return 'High'
return 'None'
except Exception:
return 'None' |
def job_fssdJ5q_imq_opt(p, data_source, tr, te, r, null_sim=None):
return job_fssdJ1q_imq_opt(p, data_source, tr, te, r, J=5) |
.experimental
def test_read_data_invalid_format(data_preparator):
with pytest.raises(ValueError, match='Invalid value of format_type.*'):
data_preparator.read_as_spark_df(path='/test_path', format_type='blabla')
with pytest.raises(ValueError, match='Either data or path parameters must not be None'):
... |
def submit_pai_evaluate(datasource, original_sql, select, label_name, model, model_params, result_table, user=''):
params = dict(locals())
project = table_ops.get_project(datasource)
if (result_table.count('.') == 0):
result_table = ('%s.%s' % (project, result_table))
params['result_table'] = re... |
class TorchSimpleFeatures(FeaturesPipeline, TabularDataFeatures):
def __init__(self, use_te: bool=False, top_intersections: int=5, max_bin_count: int=10, max_intersection_depth: int=3, te_subsample: Optional[Union[(int, float)]]=None, sparse_ohe: Union[(str, bool)]='auto', auto_unique_co: int=50, output_categories:... |
class _DiscreteQFunctionProtocol(Protocol):
_q_func_forwarder: DiscreteEnsembleQFunctionForwarder |
class QuantizeNonQNNToRecordingModifier(FunctionModifier):
def __init__(self, functions_ranks, config=None, training=True):
super(QuantizeNonQNNToRecordingModifier, self).__init__()
self._config = config
self._fct_bin_set = {'Add2': F.add2, 'Sub2': F.sub2, 'Mul2': F.mul2, 'Div2': F.div2, 'Po... |
def test_prepare_grayscale_input_2D():
with pytest.raises(ValueError):
_prepare_grayscale_input_2D(np.zeros((3, 3, 3)))
with pytest.raises(ValueError):
_prepare_grayscale_input_2D(np.zeros((3, 1)))
with pytest.raises(ValueError):
_prepare_grayscale_input_2D(np.zeros((3, 1, 1)))
_... |
def add_ConnectorServicer_to_server(servicer, server):
rpc_method_handlers = {'AllianceStatusStream': grpc.unary_stream_rpc_method_handler(servicer.AllianceStatusStream, request_deserializer=fedn__pb2.ClientAvailableMessage.FromString, response_serializer=fedn__pb2.Status.SerializeToString), 'SendStatus': grpc.unar... |
def fuzzer_bitmap_diff(fuzzers, before_fuzzer_info, after_fuzzer_info):
before_global_bitmap = before_fuzzer_info['global_bitmap']
after_bitmap = after_fuzzer_info['bitmap']
bitmap_diff = {}
for fuzzer in fuzzers:
bitmap_diff[fuzzer] = (after_bitmap[fuzzer] - before_global_bitmap)
return bit... |
def simulate_with_timeout(experiment_id, policy_name, throughputs_file, per_instance_type_prices_dir, available_clouds, assign_SLOs, cluster_spec, lam, seed, interval, fixed_job_duration, generate_multi_gpu_jobs, enable_global_queue, num_total_jobs, solver, log_dir, timeout, verbose, num_gpus_per_server, ideal, num_sub... |
_test()
def test_axpy_fpga_array():
configs = [(0.5, 1, dace.float32), (1.0, 4, dace.float64)]
return run_test(configs, 'fpga_array') |
class VGG16FeatureExtractor(nn.Module):
def __init__(self):
super().__init__()
vgg16 = models.vgg16(pretrained=True)
self.enc_1 = nn.Sequential(vgg16.features[0], vgg16.features[1], vgg16.features[2], vgg16.features[3], vgg16.features[4])
self.enc_2 = nn.Sequential(vgg16.features[5],... |
def make_act(act='ReLU', **kwargs):
inplace = kwargs.pop('inplace', True)
if (len(act) == 0):
return None
act = {'ReLU': nn.ReLU(inplace=inplace), 'ReLU6': nn.ReLU6(inplace=inplace), 'PReLU': nn.PReLU(), 'LeakyReLU': nn.LeakyReLU(inplace=inplace), 'H_Sigmoid': nn.Hardsigmoid(), 'Sigmoid': nn.Sigmoid... |
def _swig_setattr_nondynamic_method(set):
def set_attr(self, name, value):
if (name == 'thisown'):
return self.this.own(value)
if (hasattr(self, name) or (name == 'this')):
set(self, name, value)
else:
raise AttributeError(('You cannot add attributes to %s... |
class SourceCheckpoint(Callback):
_zero_only
def on_save_checkpoint(self, trainer, pl_module, checkpoint):
checkpoint_filename = ('-'.join(['source', pl_module.hparams.training_dataset.name, str(trainer.current_epoch)]) + '.pth')
os.makedirs(os.path.join(trainer.weights_save_path, 'source_checkp... |
_unique
def uninstallation_paths(dist):
r = csv.reader(FakeFile(dist.get_metadata_lines('RECORD')))
for row in r:
path = os.path.join(dist.location, row[0])
(yield path)
if path.endswith('.py'):
(dn, fn) = os.path.split(path)
base = fn[:(- 3)]
path = o... |
def normalized_fidelity(u: tf.Tensor, u_hat: tf.Tensor):
def trf(x: tf.Tensor, y=None):
y = (x if (y is None) else y)
trace = tf.linalg.trace((tf.transpose(tf.math.conj(x)) y))
return ((tf.math.real(trace) ** 2) + (tf.math.imag(trace) ** 2))
return (trf(u_hat, u) / trf(u_hat)) |
def roth_ruckenstein_root_finder(p, maxd=None, precision=None):
gens = p.parent().gens()
if (len(gens) == 2):
p = p.polynomial(gens[1])
return p.roots(multiplicities=False, degree_bound=maxd, algorithm='Roth-Ruckenstein') |
def craft_log_config(env_cfg, train_cfg, wandb_cfg, what_to_log):
for log_key in what_to_log:
location = what_to_log[log_key]
if (location[0] == 'train_cfg'):
wandb_cfg[log_key] = recursive_value_find(train_cfg, location[1:])
elif (location[0] == 'env_cfg'):
wandb_cfg... |
class env():
def __init__(self, fn_name, use_stack=True):
self.fn_name = fn_name
self.use_stack = use_stack
def __enter__(self):
start(self.fn_name, use_stack=self.use_stack)
def __exit__(self, e, ev, t):
stop(self.fn_name, use_stack=self.use_stack) |
class Node(ABC):
_prod: Production
def __init__(self, prod: Production):
self._prod = prod
def production(self) -> Production:
return self._prod
def type(self) -> Type:
return self._prod.lhs
def is_leaf(self) -> bool:
raise NotImplementedError
def is_enum(self) ->... |
def conv3d(x, w, name, s=1, pd='SAME'):
cnv = tf.nn.convolution(x, w, padding=pd, strides=[s, s, s], name=name)
return cnv |
def get_fluents(task):
fluent_names = set()
for action in task.actions:
for eff in action.effects:
fluent_names.add(eff.literal.predicate)
return [pred for pred in task.predicates if (pred.name in fluent_names)] |
def GroundSeg(depth_image, color_image, stride=160):
global ROW
virtual_lane_available = []
for i in range(stride, ROW, stride):
if (i == (ROW / 2)):
(temp_image, dead_end) = verticalGround(depth_image, color_image, i, plot=False)
else:
(temp_image, dead_end) = vertic... |
def distilhubert(refresh=False, *args, **kwargs):
return distilhubert_base(*args, refresh=refresh, **kwargs) |
class GenericGraphQuery(SQLQuery):
def __init__(self, query_string, database=None, param_tuple=None):
if (database is None):
database = GraphDatabase()
if (not isinstance(database, GraphDatabase)):
raise TypeError(('%s is not a valid GraphDatabase' % database))
SQLQue... |
def save_sparse_graph_to_npz(filepath, sparse_graph):
data_dict = {'adj_data': sparse_graph.adj_matrix.data, 'adj_indices': sparse_graph.adj_matrix.indices, 'adj_indptr': sparse_graph.adj_matrix.indptr, 'adj_shape': sparse_graph.adj_matrix.shape}
if sp.isspmatrix(sparse_graph.attr_matrix):
data_dict['at... |
_numpy_output(positive=True, check_dtype=True)
def test_ufunc_log_c(A: dace.complex64[10]):
return np.log(A) |
def append_data(dataset: str, version_target: str, version_from: str, interval=0.2):
df_target = pd.read_pickle(((DATA_ROOT / dataset) / f'{version_target}.pkl'))
df_from = pd.read_pickle(((DATA_ROOT / dataset) / f'{version_from}.pkl'))
row_num = len(df_from)
l = 0
r = (l + interval)
if (r <= 1)... |
class MOT19Wrapper(MOT17Wrapper):
def __init__(self, split, dataloader):
train_sequences = ['MOT19-01', 'MOT19-02', 'MOT19-03', 'MOT19-05']
test_sequences = ['MOT19-04', 'MOT19-06', 'MOT19-07', 'MOT19-08']
if ('train' == split):
sequences = train_sequences
elif ('test' ==... |
(message='scipy.misc.unindent_string is deprecated in Scipy 1.3.0')
def unindent_string(docstring):
return _ld.unindent_string(docstring) |
def flatten_dt(dt):
if isinstance(dt, dict):
return reduce((lambda x, y: {**x, **y}), dt.values())
else:
return reduce((lambda x, y: {**x, **y}), dt) |
def get_non_linearity(layer_type='relu'):
if (layer_type == 'relu'):
nl_layer = functools.partial(nn.ReLU, inplace=True)
elif (layer_type == 'lrelu'):
nl_layer = functools.partial(nn.LeakyReLU, negative_slope=0.2, inplace=False)
elif (layer_type == 'elu'):
nl_layer = functools.partia... |
(scope='module')
def clean_duplication_ui() -> UserInterface:
df = pd.DataFrame({'city': ['Quebec', 'Quebec', 'Quebec', 'Quebec', 'Quebec', 'quebec', 'vancouver', 'vancouver', 'vancouverr', 'Vancouver', 'Vancouver', 'Vancouver', 'van', 'Ottowa', 'Ottowa', 'otowa', 'hello', np.nan]})
return UserInterface(df, 'ci... |
_encoder('transformer')
class TransformerEncoder(Encoder):
class Config(Encoder.Config):
name: str = 'transformer'
num_segments: int = 2
bert_model_name: str = 'bert-base-uncased'
hidden_size: int = 768
num_hidden_layers: int = 12
num_attention_heads: int = 12
... |
def _evaluate_markers(markers, environment):
groups = [[]]
for marker in markers:
assert isinstance(marker, (list, tuple, string_types))
if isinstance(marker, list):
groups[(- 1)].append(_evaluate_markers(marker, environment))
elif isinstance(marker, tuple):
(lhs,... |
class WarmupMultiStepLR(torch.optim.lr_scheduler._LRScheduler):
def __init__(self, optimizer, milestones, gamma=0.1, warmup_factor=(1.0 / 3), warmup_iters=5, warmup_method='linear', last_epoch=(- 1)):
if (not (list(milestones) == sorted(milestones))):
raise ValueError('Milestones should be a lis... |
_params({'estimator': [HasMethods('fit')], 'scoring': [StrOptions(set(get_scorer_names())), callable, None], 'allow_none': ['boolean']}, prefer_skip_nested_validation=True)
def check_scoring(estimator, scoring=None, *, allow_none=False):
if isinstance(scoring, str):
return get_scorer(scoring)
if callabl... |
('/internal-server-errors/improper-input-type-handling', methods=['POST'])
def improper_input_type_handling():
data = request.json
if ((not isinstance(data, dict)) or ('number' not in data)):
return (jsonify({'success': False}), 400)
digits = [int(d) for d in str(data['number'])]
even_digits_sum... |
def test():
simple = ak.Array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5])
assert (ak.operations.to_dataframe(simple)['values'].values.tolist() == [0.0, 1.1, 2.2, 3.3, 4.4, 5.5])
index = ak.index.Index64(np.array([3, 3, 1, 5], dtype=np.int64))
indexed = ak.Array(ak.contents.IndexedArray(index, simple.layout))
as... |
def test_runtime_assert():
def prog_runtime(A: dace.float64[20]):
assert (A[0] >= 0)
A = np.random.rand(20)
prog_runtime(A) |
('/normal')
def normal():
dc = request.form['dc']
username = request.form['username']
search_filter = request.form['search_filter']
server = 'ldap://localhost'
search_base = 'dc={},dc=com'.format(dc)
ldap_conn = ldap.initialize(server)
ldap_conn.protocol_version = ldap.VERSION3
ldap_conn... |
def auresize(audio_arr, size, channel_first=False):
audio = _auresize_before(audio_arr, size, channel_first)
n_channel_num = size[1]
n_sample_num = size[0]
o_channel_num = audio.shape[1]
o_sample_num = audio.shape[0]
if ((o_channel_num != 1) and (n_channel_num != 1)):
if (o_channel_num !... |
def _construct_loader(cfg, split, batch_size, shuffle, drop_last):
dataset_name = cfg.DATA.NAME
if dataset_name.startswith('vtab-'):
from .datasets.tf_dataset import TFDataset
dataset = TFDataset(cfg, split)
else:
assert (dataset_name in _DATASET_CATALOG.keys()), "Dataset '{}' not su... |
def test_dqn():
explorer = baselines.explorers.DQN(model=fakeModel, rounds=3, sequences_batch_size=5, model_queries_per_batch=20, starting_sequence=starting_sequence, alphabet='ATCG')
explorer.run(fakeLandscape) |
class ResourceManager():
def __init__(self, owner: 'QuantumRouter', memory_array_name: str):
self.name = 'resource_manager'
self.owner = owner
self.memory_manager = MemoryManager(owner.components[memory_array_name])
self.memory_manager.set_resource_manager(self)
self.rule_man... |
def faf(df: DataFrame, num_false_positives: float, num_frames: float) -> float:
return ((num_false_positives / num_frames) * 100) |
class Real(general_dataset):
def __init__(self, root='data/meta-dataset/real', mode='test', backbone_name='resnet12', transform=None):
assert (mode in ['train', 'val', 'test'])
self.mode = mode
(_, train_process, val_process) = load(backbone_name, jit=False)
if ((mode == 'val') or (m... |
class MeanPoolGatingNetwork(torch.nn.Module):
def __init__(self, embed_dim, num_experts, dropout=None):
super().__init__()
self.embed_dim = embed_dim
self.num_experts = num_experts
self.fc1 = torch.nn.Linear(embed_dim, embed_dim)
self.dropout = (torch.nn.Dropout(dropout) if (... |
def get_sgx_docker_containers() -> List[Container]:
docker_containers = docker_client.containers.list()
return [x for x in docker_containers if (isinstance(x.attrs['HostConfig']['Devices'], list) and ('/dev/isgx' in map((lambda y: y['PathOnHost']), x.attrs['HostConfig']['Devices'])))] |
class TestMaskedLanguageModel(unittest.TestCase):
def setUp(self):
logging.disable(logging.CRITICAL)
def tearDown(self):
logging.disable(logging.NOTSET)
def test_legacy_masked_lm(self):
with contextlib.redirect_stdout(StringIO()):
with tempfile.TemporaryDirectory('test_le... |
class Version(_BaseVersion):
_regex = re.compile((('^\\s*' + VERSION_PATTERN) + '\\s*$'), (re.VERBOSE | re.IGNORECASE))
def __init__(self, version):
match = self._regex.search(version)
if (not match):
raise InvalidVersion("Invalid version: '{0}'".format(version))
self._versio... |
class Vocab(object):
def __init__(self, vocab_file, max_size):
self._word_to_id = {}
self._id_to_word = {}
self._count = 0
with open(vocab_file, 'r') as vocab_f:
for line in vocab_f:
pieces = line.split()
if (len(pieces) != 2):
... |
def named_tensor():
tensor = base_pb2.NamedTensor(name='tensor_name', round_number=0, lossless=False, report=False, data_bytes=(32 * b'1'))
tensor.tags.append('model')
metadata = tensor.transformer_metadata.add()
metadata.int_to_float[1] = 1.0
metadata.int_list.extend([1, 8])
metadata.bool_list.... |
def deco(name):
f = getattr(windows, name)
def wrapped(*args, **kwargs):
return f(*args, **kwargs)
wrapped.__name__ = name
wrapped.__module__ = 'scipy.signal'
if hasattr(f, '__qualname__'):
wrapped.__qualname__ = f.__qualname__
if f.__doc__:
lines = f.__doc__.splitlines()... |
def select_unit(t: float):
time_unit = {(- 3): 'ns', (- 2): 'us', (- 1): 'ms'}.get(int((np.log10(t) // 3)), 's')
time_scale = {'ns': 1e-09, 'us': 1e-06, 'ms': 0.001, 's': 1}[time_unit]
return (time_unit, time_scale) |
class AutoUplift(BaseAutoUplift):
def __init__(self, base_task: Task, uplift_candidates: List[MetaLearnerWrapper]=[], add_dd_candidates: bool=False, metric: Union[(str, TUpliftMetric, Callable)]='adj_qini', has_report: bool=False, increasing_metric: bool=True, test_size: float=0.2, threshold_imbalance_treatment: fl... |
('ir_labeled_tuple_loader')
class IrLabeledTupleDatasetReader(DatasetReader):
def __init__(self, tokenizer: Tokenizer=None, token_indexers: Dict[(str, TokenIndexer)]=None, source_add_start_token: bool=True, max_doc_length: int=(- 1), max_query_length: int=(- 1), lazy: bool=False) -> None:
super().__init__(l... |
def save_checkpoint(config, epoch, model, max_accuracy, optimizer, lr_scheduler, logger):
save_state = {'model': model.state_dict(), 'optimizer': optimizer.state_dict(), 'lr_scheduler': lr_scheduler.state_dict(), 'max_accuracy': max_accuracy, 'epoch': epoch, 'config': config}
if (config.AMP_OPT_LEVEL != 'O0'):
... |
()
class Checkpoint():
def __init__(self, checkpoint_dir: str, patience: Optional[int]=7, delta: Optional[float]=0.0):
self.checkpoint_dir = checkpoint_dir
self.model_path = join(checkpoint_dir, 'model.pth')
self.patience = patience
self.counter = 0
self.best_loss = float('in... |
def build_scheduler(cfg, optimizer):
return SCHEDULERS.build(cfg, default_args=dict(optimizer=optimizer)) |
def _from_whatever(data, fmt=None):
from sage.graphs.graph import Graph
if isinstance(data, str):
lines = data.splitlines()
else:
lines = try_read(data, splitlines=True)
if ((lines is not None) and (fmt is None)):
if hasattr(data, 'name'):
if data.name.end... |
def test_affinity_map_construction():
arr = np.random.rand(3, 3, 4, 5).astype(np.float32)
aff = AffinityMap(arr, voxel_offset=(0, (- 1), (- 1), (- 1))) |
class T5():
def __init__(self, config):
self.batch_size = config['batch_size']
self.tokenizer = T5Tokenizer.from_pretrained(config['model_weights'])
self.model = T5ForConditionalGeneration.from_pretrained(config['model_weights'])
self.page_retrieval = (config['page_retrieval'].lower(... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--user_weights_file', required=True)
parser.add_argument('--item_weights_file', required=True)
parser.add_argument('--output_dir', required=True)
args = parser.parse_args()
print('Saving item weights....')
item_mat = mmread(... |
def test_estimate_bandwidth_1sample(global_dtype):
bandwidth = estimate_bandwidth(X.astype(global_dtype, copy=False), n_samples=1, quantile=0.3)
assert (bandwidth.dtype == X.dtype)
assert (bandwidth == pytest.approx(0.0, abs=1e-05)) |
class F1Scorer(Scorer):
def keys(self) -> Set[str]:
return {'f1'}
def _score_single_ref(self, context: str, questions: List[str], answers: List[str], predictions: List[str], probabilities: List[float], null_probabilities: List[float]) -> List[Dict[(str, float)]]:
scores = []
for (predict... |
_converter_regitstry('DMA_compress')
def DMA_compress_converter(context: 'BM1688Context', reg: DMA_compress_reg):
return (([],) * 3) |
class SKFF(nn.Module):
def __init__(self, in_channels, height=3, reduction=8, bias=False):
super(SKFF, self).__init__()
self.height = height
d = max(int((in_channels / reduction)), 4)
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.conv_du = nn.Sequential(nn.Conv2d(in_channels, ... |
_params
def test_quad_vec_simple_inf(quadrature):
f = (lambda x: (1 / (1 + (np.float64(x) ** 2))))
for epsabs in [0.1, 0.001, 1e-06]:
if ((quadrature == 'trapz') and (epsabs < 0.0001)):
continue
kwargs = dict(norm='max', epsabs=epsabs, quadrature=quadrature)
(res, err) = quad... |
def mfp2d(arr, xth=0.5, iterations=1000000, verbose=True, point='random'):
info = arr.shape
longy = max([info[0], info[1]])
longest = int((np.sqrt(2) * longy))
num_sz = np.zeros(longest)
ar = np.zeros(arr.shape)
ar[(arr >= xth)] = 1
thetas = np.random.randint(0, 360, size=iterations)
ls ... |
def BruckRyserChowla_check(v, k, lambd):
from sage.rings.rational_field import QQ
if ((k * (k - 1)) != (lambd * (v - 1))):
return Unknown
if ((v % 2) == 0):
return is_square((k - lambd))
g = (1 if ((v % 4) == 1) else (- 1))
C = Conic(QQ, [1, (lambd - k), ((- g) * lambd)])
(flag, ... |
def get_notebooks(tutorial_dir: str) -> List[Notebook]:
path = os.path.abspath(tutorial_dir)
config_path = os.path.join(path, NOTEBOOKS_CONFIG_FNAME)
if (not os.path.isfile(config_path)):
logging.info(f'No {NOTEBOOKS_CONFIG_FNAME} config file in {path}')
return []
with open(config_path, ... |
def parse_stage_factory(context):
def parse(compsrc):
source_desc = compsrc.source_desc
full_module_name = compsrc.full_module_name
initial_pos = (source_desc, 1, 0)
(saved_cimport_from_pyx, Options.cimport_from_pyx) = (Options.cimport_from_pyx, False)
scope = context.find_mo... |
def visible_gpu(gpus):
gpus = ([gpus] if isinstance(gpus, int) else list(gpus))
os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(list(map(str, gpus)))
return list(range(len(gpus))) |
def test_analyse_module(parsed_module_no_dependencies):
test_cluster = analyse_module(parsed_module_no_dependencies)
assert (test_cluster.num_accessible_objects_under_test() == 4) |
class RandomPolicy(QLearningAlgoBase[(None, RandomPolicyConfig)]):
_action_size: int
def __init__(self, config: RandomPolicyConfig):
super().__init__(config, False, None)
self._action_size = 1
def inner_create_impl(self, observation_shape: Shape, action_size: int) -> None:
self._acti... |
(0.1)
('/get_tv_plan', methods=['POST'])
def funcGetTVPlanPrice():
dm_msg = request.json['entities']
entity_name = 'new_tv_plan'
tvplan = dm_msg[entity_name]
price = {'hulu live': 200, 'hulu tv': 200, 'fubo tv': 300, 'pluto tv': 500}
try:
return json_resp(True, 'the price of {} is {} dollar ... |
class LazyInstanceNorm2d(_LazyNormBase, _InstanceNorm):
cls_to_become = InstanceNorm2d
def _check_input_dim(self, input):
if (input.dim() != 4):
raise ValueError('expected 4D input (got {}D input)'.format(input.dim())) |
def evaluate_conll(gold_path, predictions, official_stdout=False):
with tempfile.NamedTemporaryFile(delete=False, mode='w') as prediction_file:
with open(gold_path, 'r') as gold_file:
output_conll(gold_file, prediction_file, predictions)
print('Predicted conll file: {}'.format(prediction... |
def clear():
if (not isatty(sys.stdout)):
return
if WIN:
os.system('cls')
else:
sys.stdout.write('\x1b[2J\x1b[1;1H') |
def print_banner():
print('/\\')
print('| |')
print('| BLASYS -- Approximate Logic Synthesis Using Boolean Matrix Factorization |')
print('| Version: {} |'.format(__version... |
def unpack_string_to_character_literals(literal):
chars = []
pos = literal.pos
stype = literal.__class__
sval = literal.value
sval_type = sval.__class__
for char in sval:
cval = sval_type(char)
chars.append(stype(pos, value=cval, constant_result=cval))
return chars |
def get_norm_act_layer(layer_class):
layer_class = layer_class.replace('_', '').lower()
if layer_class.startswith('batchnorm'):
layer = BatchNormAct2d
elif layer_class.startswith('groupnorm'):
layer = GroupNormAct
elif (layer_class == 'evonormbatch'):
layer = EvoNormBatch2d
e... |
def all_cached_data(polytopes):
all_polars(polytopes)
all_points(polytopes)
reflexive = [p for p in polytopes if p.is_reflexive()]
all_nef_partitions(reflexive)
polar = [p.polar() for p in reflexive]
all_points(polar)
all_nef_partitions(polar) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.