code stringlengths 101 5.91M |
|---|
def register_Ns3RrcConnectionReconfigurationCompleteHeader_methods(root_module, cls):
cls.add_constructor([param('ns3::RrcConnectionReconfigurationCompleteHeader const &', 'arg0')])
cls.add_constructor([])
cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'bIterator')], is_virtual=Tr... |
class Datagen_tree():
def __init__(self, X, Y, batch_size, code_dic, nl_dic, train=True, binary=False):
self.X = X
self.Y = Y
self.batch_size = batch_size
self.code_dic = code_dic
self.nl_dic = nl_dic
self.train = train
self.binary = binary
def __len__(sel... |
def accuracy_ent(network, loader, weights, device, adapt=False):
correct = 0
total = 0
weights_offset = 0
ent = 0
network.eval()
with torch.no_grad():
for (x, y) in loader:
x = x.to(device)
y = y.to(device)
if (adapt is None):
p = netwo... |
class Sampler():
def __init__(self, sp_i_train):
random.seed(42)
self._train = sp_i_train
def step(self, users: int, batch_size: int):
train = self._train
shuffled_list = random.sample(range(users), users)
for start_idx in range(0, users, batch_size):
end_idx ... |
class BatchGenerator():
def __init__(self, weather_data, val_ratio, test_ratio, normalize_flag, params):
self.weather_data = weather_data
self.val_ratio = val_ratio
self.test_ratio = test_ratio
self.dataset_params = params
self.normalize_flag = normalize_flag
if self.... |
class FileBatchGenerator(BatchGenerator):
def __init__(self, file, n_jobs: int=1, batch_size: Optional[int]=None, read_csv_params: dict=None):
super().__init__(batch_size, n_jobs)
self.file = file
(self.offsets, self.cnts) = get_file_offsets(file, n_jobs, batch_size)
if (read_csv_par... |
class DNNLowPChannelShuffleOpsTest(hu.HypothesisTestCase):
(channels_per_group=st.integers(min_value=1, max_value=5), groups=st.sampled_from([1, 4, 8, 9]), n=st.integers(0, 2), order=st.sampled_from(['NCHW', 'NHWC']), **hu.gcs_cpu_only)
(max_examples=10, deadline=None)
def test_channel_shuffle(self, channel... |
def force_image_sizes(dataset, image_size=(96, 96)):
reshape_images = (lambda image, label: (tf.image.resize(image, image_size), label))
dataset = dataset.map(reshape_images, num_parallel_calls=AUTO)
return dataset |
class BlurFunction(Function):
def forward(ctx, input, kernel, kernel_flip):
ctx.save_for_backward(kernel, kernel_flip)
output = F.conv2d(input, kernel, padding=1, groups=input.shape[1])
return output
def backward(ctx, grad_output):
(kernel, kernel_flip) = ctx.saved_tensors
... |
def random_new_basis_modp(N, p, k, LWBModp, TotalBasisModp, elldash, bound):
R = LWBModp[0][0].parent()
if (k == 0):
TotalBasisModp[(0, 0)] = 1
return [[]]
di = dimension_modular_forms(N, k)
diminus1 = dimension_modular_forms(N, (k - (p - 1)))
mi = (di - diminus1)
NewBasisCode = ... |
_numpy_output(validation_func=(lambda a: (- a)))
def test_ufunc_negative_u(A: dace.uint32[10]):
return np.negative(A) |
def download_file_from_google_drive(id, destination):
def get_confirm_token(response):
for (key, value) in response.cookies.items():
if key.startswith('download_warning'):
return value
return None
def save_response_content(response, destination):
CHUNK_SIZE = ... |
def get_worker_runtimes(jobs, num_jobs=None):
runtimes = {}
if (num_jobs is None):
num_jobs = len(jobs)
max_end_time = get_job_end_times(jobs)[(num_jobs - 1)][0]
overall_execution_time = get_overall_execution_time(jobs, max_end_time)
for job_id in jobs:
job = jobs[job_id]
met... |
class Simulator():
def __init__(self, task: Task, simulator: Callable, max_calls: Optional[int]=None):
self.simulator = simulator
self.max_calls = max_calls
self.num_simulations = 0
self.name = task.name
self.dim_data = task.dim_data
self.dim_parameters = task.dim_par... |
_utils.test(require=ti.extension.bls)
def test_gather_1d_trivial():
_test_bls_stencil(1, 128, bs=32, stencil=((0,),)) |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, act_cfg=dict(type='ReLU'), conv_cfg=None, norm_cfg=dict(type='BN'), with_cp=False):
super(Bottleneck, self).__init__()
self.inplanes = inplanes
self.planes = planes
... |
def filter_not_valid(df_keypoints):
def check_valid(x):
kp_array = pose_utils.load_pose_cords_from_strings(x['keypoints_y'], x['keypoints_x'])
distractor = (x['name'].startswith('-1') or x['name'].startswith('0000'))
return (pose_check_valid(kp_array) and (not distractor))
return df_keyp... |
def _replace_stopwords(text: Any, value: str, stopwords: Optional[Set[str]]=None) -> Any:
if pd.isna(text):
return text
stopwords = (english_stopwords if (not stopwords) else stopwords)
return ' '.join(((word if (word.lower() not in stopwords) else value) for word in str(text).split())) |
class GraphAppendingTracer(TracerBase):
def __init__(self, graph: Graph):
super().__init__()
self.graph = graph |
def run_ngram_baseline(train_fpath, test_fpath):
train_df = pd.read_csv(train_fpath, sep='\t')
test_df = pd.read_csv(test_fpath, sep='\t')
pipeline = Pipeline([('ngrams', TfidfVectorizer(ngram_range=(1, 1))), ('clf', SVC(C=1, gamma=0.75, kernel='rbf', random_state=0))])
pipeline.fit(train_df['tweet_text... |
def average_seed(all_seed_dict):
result_mean = {}
result_std = {}
for term in RESULTS_TERMS:
result = []
for seed in all_seed_dict.keys():
if (term in all_seed_dict[seed].keys()):
result.append(all_seed_dict[seed][term])
elif (term == 'Closed-set OA'):... |
class JasperBlock(nn.Module):
def __init__(self, num_sub_blocks: int, in_channels: int, out_channels: int, kernel_size: int, stride: int=1, dilation: int=1, bias: bool=True, dropout_p: float=0.2, activation: str='relu') -> None:
super(JasperBlock, self).__init__()
padding = self.get_same_padding(ker... |
def scorep_env(tmp_path):
env = os.environ.copy()
env['SCOREP_ENABLE_PROFILING'] = 'false'
env['SCOREP_ENABLE_TRACING'] = 'true'
env['SCOREP_PROFILING_MAX_CALLPATH_DEPTH'] = '98'
env['SCOREP_TOTAL_MEMORY'] = '3G'
env['SCOREP_EXPERIMENT_DIRECTORY'] = str((tmp_path / 'test_bindings_dir'))
retu... |
class ResidualCNN(nn.Module):
def __init__(self, in_channels, out_channels, kernel, stride, dropout, n_feats):
super(ResidualCNN, self).__init__()
self.cnn1 = nn.Conv2d(in_channels, out_channels, kernel, stride, padding=(kernel // 2))
self.cnn2 = nn.Conv2d(out_channels, out_channels, kernel,... |
def spearman(x, y, impute_nan=True):
if impute_nan:
x = torch.nan_to_num(x)
y = torch.nan_to_num(y)
if (torch.all((y == y[1])) or torch.all((x == x[1]))):
x = np.array(x.cpu())
y = np.array(y.cpu())
return np.array([0.5 for (_, _) in zip(np.rollaxis(x, 1), np.rollaxis(y, ... |
class FillPlan(BenchmarkPlan):
def __init__(self, arch: str):
super().__init__('fill', arch, basic_repeat_times=10)
fill_container = Container()
fill_container.update({'sparse': None})
self.create_plan(fill_container, DataType(), DataSize(), MetricType())
self.add_func(['fiel... |
_checkpoint_hooks
class CyclicLRScheduler():
def __init__(self, base_lr=0.001, max_lr=0.006, step_size=2000.0, mode='triangular', gamma=1.0, scale_fn=None, scale_mode='cycle'):
super(CyclicLRScheduler, self).__init__()
self.losses = []
self.base_lr = base_lr
self.max_lr = max_lr
... |
class TokenClassificationArgumentHandlerTestCase(unittest.TestCase):
def setUp(self):
self.args_parser = TokenClassificationArgumentHandler()
def test_simple(self):
string = 'This is a simple input'
(inputs, offset_mapping) = self.args_parser(string)
self.assertEqual(inputs, [str... |
class LinearCodeNearestNeighborDecoder(Decoder):
def __init__(self, code):
super().__init__(code, code.ambient_space(), code._default_encoder_name)
def __eq__(self, other):
return (isinstance(other, LinearCodeNearestNeighborDecoder) and (self.code() == other.code()))
def _repr_(self):
... |
def _swig_repr(self):
try:
strthis = ('proxy of ' + self.this.__repr__())
except Exception:
strthis = ''
return ('<%s.%s; %s >' % (self.__class__.__module__, self.__class__.__name__, strthis)) |
class AverageMeter():
def __init__(self, dataset):
self.benchmark = dataset.benchmark
if (self.benchmark == 'pascal'):
self.class_ids_interest = dataset.class_ids
self.class_ids_interest = torch.tensor(self.class_ids_interest).cuda()
self.nclass = 20
elif ... |
def test_authorization_warning_missing_threshold(result):
result.checks.extend([make_check(201), make_check(401)])
assert (not has_too_many_responses_with_status(result, 401)) |
def convert_worldwide_file(filename, short_name):
assert ('en_worldwide-9class.' in filename)
if (not os.path.exists(filename)):
raise FileNotFoundError(('Cannot convert missing file %s' % filename))
new_filename = filename.replace('en_worldwide-9class.', (short_name + '.worldwide-9class.'))
wit... |
class CollateMergedPseudo():
def __init__(self, device=None):
self.device = device
def __call__(self, list_data):
source_list_data = []
target_list_data = []
target_list_pseudo = []
source_selected = []
target_selected = []
source_idx = []
target_i... |
def run(env, num_envs, total_step, async_):
if (env == 'atari'):
task_id = 'PongNoFrameskip-v4'
frame_skip = 4
if (num_envs == 1):
env = wrap_deepmind(gym.make(task_id), episode_life=False, clip_rewards=False, frame_stack=4)
else:
env = gym.vector.make(task_id... |
class XORHyperplaneClassifier(nn.Module):
def __init__(self, x_dim, y_dim, P1, P2, a1=None, a2=None, b1=None, b2=None, ksig=5):
super(XORHyperplaneClassifier, self).__init__()
if (a1 is None):
self.a1 = Parameter(torch.matmul(torch.randn(int(y_dim), int(x_dim)), torch.t(P1)))
els... |
class RandomPolicy(BasePolicy):
def __init__(self):
super().__init__()
def forward(self, observation, available_actions):
if available_actions['has_search_bar']:
action = 'search[shoes]'
else:
action_arg = random.choice(available_actions['clickables'])
... |
def load_conllu(file, treebank_type):
class UDRepresentation():
def __init__(self):
self.characters = []
self.tokens = []
self.words = []
self.sentences = []
class UDSpan():
def __init__(self, start, end):
self.start = start
... |
def init_ddp():
try:
local_rank = int(os.environ['LOCAL_RANK'])
world_size = int(os.environ['WORLD_SIZE'])
except KeyError:
return (0, 1)
dist.init_process_group(backend='nccl')
print(f'Initialized process {local_rank} / {world_size}')
torch.cuda.set_device(local_rank)
se... |
def _ensure_dask_array(array, chunks=None):
import dask.array as da
if isinstance(array, da.Array):
return array
return da.from_array(array, chunks=chunks) |
def register_Ns3EpcS11SapSgwDeleteBearerResponseMessage_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::EpcS11SapSgw::DeleteBearerResponseMessage const &', 'arg0')])
cls.add_instance_attribute('bearerContextsRemoved', 'std::list< ns3::EpcS11SapSgw::BearerContextRemovedSgw... |
def skip_torch_module_member(app, what, name, obj, skip, options):
skip_torch = (('Module.' in str(obj)) and (name in dir(torch.nn.Module)))
if (name == 'dump_patches'):
skip_torch = True
return (skip or skip_torch) |
class ToysCalculator(BaseToysCalculator, ToysManager):
def __init__(self, input, minimizer, ntoysnull: int=100, ntoysalt: int=100, sampler: Callable=base_sampler, sample: Callable=base_sample):
super().__init__(input, minimizer, sampler, sample)
self._ntoysnull = ntoysnull
self._ntoysalt = n... |
def test_UnmaskedArray():
a = ak.contents.unmaskedarray.UnmaskedArray(ak.contents.numpyarray.NumpyArray(np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6])))
b = ak.contents.unmaskedarray.UnmaskedArray(ak.contents.numpyarray.NumpyArray(np.array([7.7, 8.8, 9.9])))
c = ak.concatenate([a, b])
ctt = ak.concatenate([a.... |
class NotEq(AttributeFilter):
def __init__(self, attr: str, value: Any):
super().__init__(attr=attr, value=value, op=operator.ne)
def op_as_str(self):
return '!=' |
def fetch_logged_data(run_id):
client = mlflow.MlflowClient()
data = client.get_run(run_id).data
artifacts = [f.path for f in client.list_artifacts(run_id, 'model')]
return (data.params, data.metrics, artifacts) |
class CheckpointTest(unittest.TestCase):
def test_load_pretrained(self):
create_checkpoint('testing', './testing.npz')
model = models.KNOWN_MODELS['testing'].partial(num_classes=2)
(_, params) = model.init_by_shape(jax.random.PRNGKey(0), [((1, 32, 32, 3), jnp.float32)])
logger = logg... |
class QuaternionAlgebraFactory(UniqueFactory):
def create_key(self, arg0, arg1=None, arg2=None, names='i,j,k'):
if ((arg1 is None) and (arg2 is None)):
K = QQ
D = Integer(arg0)
(a, b) = hilbert_conductor_inverse(D)
a = Rational(a)
b = Rational(b)
... |
def save_model(args, epoch, model, model_without_ddp, optimizer, loss_scaler, model_ema=None, optimizer_disc=None, save_ckpt_freq=1):
output_dir = Path(args.output_dir)
epoch_name = str(epoch)
if (not getattr(args, 'enable_deepspeed', False)):
checkpoint_paths = [(output_dir / 'checkpoint.pth')]
... |
def generate_images(images_dir, examples_dir, pattern='*.py'):
from sfepy.applications import solve_pde
from sfepy.solvers.ts_solvers import StationarySolver
prefix = output.prefix
output_dir = tempfile.mkdtemp()
trunk = os.path.join(output_dir, 'result')
options = Struct(output_filename_trunk=t... |
def replay_trace():
current_time = initial_time_trace
index_start = 0
while (index_start < len(jobs_by_start_time)):
created = []
try:
while (jobs_by_start_time[index_start][1] <= current_time):
created.append(jobs_by_start_time[index_start])
index... |
class Narrow(Module):
def __init__(self, dimension, offset, length=1):
super(Narrow, self).__init__()
self.dimension = dimension
self.index = offset
self.length = length
def updateOutput(self, input):
length = self.length
if (length < 0):
length = (((i... |
class AFLModel(BaseModel):
seed = peewee.CharField()
output = peewee.CharField()
group = peewee.CharField()
program = peewee.CharField()
argument = peewee.CharField()
master = peewee.BooleanField()
pid = peewee.IntegerField()
fuzzer_id = peewee.IntegerField(unique=True) |
def print_network(model, name, out_file=None):
num_params = 0
for p in model.parameters():
num_params += p.numel()
if (out_file is None):
print(name)
print(model)
print('The number of parameters: {}'.format(num_params))
else:
with open(out_file, 'w') as f:
... |
class SpeakerDependentTAVConfig(Config):
use_target_text = True
use_target_audio = True
use_target_video = True
svm_c = 10.0 |
class ModulatedDeformConvPack(ModulatedDeformConv):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, deformable_groups=1, bias=True):
super(ModulatedDeformConvPack, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, ... |
class ForScope(ControlFlow):
itervar: str
guard: SDFGState
init: str
condition: CodeBlock
update: str
body: GeneralBlock
init_edges: List[InterstateEdge]
def as_cpp(self, codegen, symbols) -> str:
sdfg = self.guard.parent
defined_vars = codegen.dispatcher.defined_vars
... |
def bi_interaction(x_h, x_l):
sizeH = (int(x_h.shape[(- 2)]), int(x_h.shape[(- 1)]))
sizeL = (int(x_l.shape[(- 2)]), int(x_l.shape[(- 1)]))
o_h = (x_h + upsample(x_l, sizeH))
o_l = (x_l + upsample(x_h, sizeL))
return (o_h, o_l) |
class CommonVoiceDataset(Dataset):
def __init__(self, split, tokenizer, bucket_size, path, ascending=False, ratio=1.0, offset=0, **kwargs):
self.path = path
self.bucket_size = bucket_size
for s in split:
with open(s, 'r') as fp:
rows = csv.reader(fp, delimiter='\t... |
_module()
class ResNetDec(nn.Module):
def __init__(self, block, layers, in_channels, kernel_size=3, conv_cfg=None, norm_cfg=dict(type='BN'), act_cfg=dict(type='LeakyReLU', negative_slope=0.2, inplace=True), with_spectral_norm=False, late_downsample=False):
super().__init__()
if (block == 'BasicBlock... |
def _variables_recursive(R, include=None, exclude=None):
if ((include is not None) and (exclude is not None)):
raise RuntimeError('include and exclude cannot both be specified')
if (include is not None):
degree_one = [R(g) for g in include]
else:
try:
degree_one = [R(g) f... |
def str_visible_len(s):
import re
s = re.sub('[\x1b\x9b][\\[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]', '', s)
return len(s) |
def test_testsuite_statement_checked_coverage_calculation(plus_three_test):
module_name = 'tests.fixtures.linecoverage.plus'
test_suite = tsc.TestSuiteChromosome()
test_suite.add_test_case_chromosome(tcc.TestCaseChromosome(test_case=plus_three_test))
config.configuration.statistics_output.coverage_metri... |
def t_div(u: fenics.Function, n: fenics.FacetNormal) -> ufl_expr.Expr:
return (fenics.div(u) - fenics.inner((fenics.grad(u) * n), n)) |
_torch
class MLukeTokenizerIntegrationTests(unittest.TestCase):
tokenizer_class = MLukeTokenizer
from_pretrained_kwargs = {'cls_token': '<s>'}
def setUpClass(cls):
cls.tokenizer = MLukeTokenizer.from_pretrained('studio-ousia/mluke-base', return_token_type_ids=True)
cls.entity_classification_... |
def _process_image_files_batch(coder, thread_index, ranges, name, filenames, texts, labels, num_shards):
num_threads = len(ranges)
assert (not (num_shards % num_threads))
num_shards_per_batch = int((num_shards / num_threads))
shard_ranges = np.linspace(ranges[thread_index][0], ranges[thread_index][1], (... |
def load_soba_json(json_file, image_root, dataset_name=None):
from pysobatools.soba import SOBA
timer = Timer()
json_file = PathManager.get_local_path(json_file)
with contextlib.redirect_stdout(io.StringIO()):
soba_api = SOBA(json_file)
if (timer.seconds() > 1):
logger.info('Loading ... |
_utils.test()
def test_listcomp():
def identity(dt, n: ti.template()):
return ti.Matrix([[ti.cast(int((i == j)), dt) for j in range(n)] for i in range(n)])
def foo(n: ti.template()) -> ti.i32:
a = identity(ti.i32, n)
b = [j for i in a for j in i]
ret = 0
for i in ti.stati... |
def draw(G, c, x, ax, draw_edge=True, font_size=0, pos=None, cmap=None, max_group_num=None, draw_nodes_kwd={}, draw_edges_kwd={'edge_color': '#adadad'}, draw_labels_kwd={}, layout_algorithm=None):
(colored_nodes, muted_nodes, residuals) = classify_nodes(G, c, x, max_group_num)
(node_colors, node_edge_colors) = ... |
class OldNSZ(BaseSMTEncoder):
def _float_binary_operator(self, term, op):
x = self.eval(term.x)
y = self.eval(term.y)
if ('nnan' in term.flags):
self.add_defs(z3.Not(z3.fpIsNaN(x)), z3.Not(z3.fpIsNaN(y)), z3.Not(z3.fpIsNaN(op(x, y))))
if ('ninf' in term.flags):
... |
def visualize_ner_str(text, pipe, select=None, colors=None):
doc = pipe(text)
visualize_ner_doc(doc, pipe.lang, select, colors) |
def callback_image(data):
try:
cv_image = cv_bridge.imgmsg_to_cv2(data, 'bgr8')
except CvBridgeError as e:
rospy.logerr(('[tf-pose-estimation] Converting Image Error. ' + str(e)))
return
acquired = tf_lock.acquire(False)
if (not acquired):
return
try:
humans =... |
def validate_kr_rrn(df: Union[(str, pd.Series, dd.Series, pd.DataFrame, dd.DataFrame)], column: str='') -> Union[(bool, pd.Series, pd.DataFrame)]:
if isinstance(df, (pd.Series, dd.Series)):
return df.apply(rrn.is_valid)
elif isinstance(df, (pd.DataFrame, dd.DataFrame)):
if (column != ''):
... |
def create_dummy_data(data_dir, num_examples=100, maxlen=20, alignment=False):
def _create_dummy_data(filename):
data = torch.rand((num_examples * maxlen))
data = (97 + torch.floor((26 * data)).int())
with open(os.path.join(data_dir, filename), 'w') as h:
offset = 0
f... |
class SGD(torch.optim.Optimizer):
def __init__(self, params, lr=0.1, momentum=0, dampening=0, weight_decay=0, nesterov=False):
defaults = dict(lr=lr, momentum=momentum, dampening=dampening, weight_decay=weight_decay, nesterov=nesterov)
if (nesterov and ((momentum <= 0) or (dampening != 0))):
... |
def sample_procedural_objects(task_base, num_samples, mass=0.1):
assets_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../assets/procedural_objects')
samples = np.random.choice(os.listdir(assets_dir), num_samples, replace=False)
created = []
for s in samples:
respondable = os.pa... |
def generate_data(data_dir='heterogeneous_example_data', verbose=True):
if (data_dir[(- 1)] != '/'):
data_dir += '/'
if (not os.path.exists(data_dir)):
os.makedirs(data_dir)
data_filename = (data_dir + 'heterogeneous_example_data.json')
sample_sizes = [100, 200, 500, 1000, 2000]
illi... |
def getsourcelines(obj):
with _InspectContextManager():
return inspect.getsourcelines(obj) |
def register_Ns3ExtendedSupportedRatesIE_methods(root_module, cls):
cls.add_constructor([param('ns3::ExtendedSupportedRatesIE const &', 'arg0')])
cls.add_constructor([])
cls.add_constructor([param('ns3::SupportedRates *', 'rates')])
cls.add_method('DeserializeInformationField', 'uint8_t', [param('ns3::B... |
class Block35(nn.Module):
def __init__(self, scale=1.0):
super(Block35, self).__init__()
self.scale = scale
self.branch0 = BasicConv2d(320, 32, kernel_size=1, stride=1)
self.branch1 = nn.Sequential(BasicConv2d(320, 32, kernel_size=1, stride=1), BasicConv2d(32, 32, kernel_size=3, stri... |
def universal_sentence_embedding(sentences, mask, sqrt=True):
sentence_sums = torch.bmm(sentences.permute(0, 2, 1), mask.float().unsqueeze((- 1))).squeeze((- 1))
divisor = mask.sum(dim=1).view((- 1), 1).float()
if sqrt:
divisor = divisor.sqrt()
sentence_sums /= divisor
return sentence_sums |
def register_Ns3RipRte_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_constructor([param('ns3::RipRte const &', 'arg0')])
cls.add_constructor([])
cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True)
cls.add_method('GetInstanceType... |
def register_Ns3DsrDsrOptionSR_methods(root_module, cls):
cls.add_constructor([param('ns3::dsr::DsrOptionSR const &', 'arg0')])
cls.add_constructor([])
cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True)
cls.add_method('GetOptionNumber', 'uint8_t', [], is_const=True, i... |
def get_class_weight_from_file(n_class, weight_filename=None, add_bg_loss=False):
weight = torch.ones(n_class)
if weight_filename:
import pandas as pd
loss_df = pd.read_csv(weight_filename)
loss_df.sort_values('class_id', inplace=True)
weight *= torch.FloatTensor(loss_df.weight.v... |
def _check_special_BC_cases(dg, n, check_letter_list, check_twist_list, hope_letter_list, conn_vert_list=False):
if (not dg.is_connected()):
return 'unknown'
if conn_vert_list:
mut_type = _connected_mutation_type_AAtildeD(dg, ret_conn_vert=True)
if (not (mut_type == 'unknown')):
... |
def test_brent_underflow_in_root_bracketing():
underflow_scenario = ((- 450.0), (- 350.0), (- 400.0))
overflow_scenario = (350.0, 450.0, 400.0)
for (a, b, root) in [underflow_scenario, overflow_scenario]:
c = np.exp(root)
for method in [zeros.brenth, zeros.brentq]:
res = method((... |
def run():
logger = config.get_logger('train')
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
if (config['visualizer']['type'] != ''):
visualizer = config.initialize(name='visualizer', module=module_vis, exp_name=config['name'], web_dir=config._web_log_dir)
else:
visualizer = None
to... |
class ToTensor(object):
def __call__(self, img, gt):
return (F.to_tensor(img), F.to_tensor(gt)) |
def test_conversion(Poly1, Poly2):
x = np.linspace(0, 1, 10)
coef = random((3,))
d1 = (Poly1.domain + (random((2,)) * 0.25))
w1 = (Poly1.window + (random((2,)) * 0.25))
p1 = Poly1(coef, domain=d1, window=w1)
d2 = (Poly2.domain + (random((2,)) * 0.25))
w2 = (Poly2.window + (random((2,)) * 0.2... |
def mp_fit(epochs: int, learn: Learner, callbacks: Optional[CallbackList]=None, metrics: OptMetrics=None) -> None:
assert (len(learn.data.train_dl) != 0), f'''Your training dataloader is empty, can't train a model.
Use a smaller batch size (batch size={learn.data.train_dl.batch_size} for {len(learn.data.tra... |
class ThroughputTable(PerformanceTable):
def __init__(self, percentiles, unit='tok/s', reverse_percentiles=True):
super().__init__(percentiles, unit, reverse_percentiles)
self.unit_convert = {'tok/s': 1} |
class _netD(nn.Module):
def __init__(self, ngpu):
super(_netD, self).__init__()
self.ngpu = ngpu
self.main = nn.Sequential(nn.Conv2d(nc, ndf, 4, 2, 1, bias=False), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(ndf, (ndf * 2), 4, 2, 1, bias=False), nn.BatchNorm2d((ndf * 2)), nn.LeakyReLU(0.2, in... |
def test():
array = ak.highlevel.Array([[[0.0, 1.1, 2.2], []], [[3.3, 4.4]], [], [[5.5], [], [6.6, 7.7, 8.8, 9.9]]])
assert (to_list(ak.operations.local_index(array, axis=0)) == [0, 1, 2, 3])
assert (to_list(ak.operations.local_index(array, axis=1)) == [[0, 1], [0], [], [0, 1, 2]])
assert (to_list(ak.op... |
def _apply_fc_weight_for_sum_match(model, input, dim_in, dim_out, scope, name):
output = brew.fc(model, input, s(scope, name), dim_in=dim_in, dim_out=dim_out, axis=2)
output = model.net.Squeeze(output, output, dims=[0])
return output |
def run_ete(paths, dataset, short_name, command_args, extra_args):
(short_language, package) = short_name.split('_', 1)
tokenize_dir = paths['TOKENIZE_DATA_DIR']
mwt_dir = paths['MWT_DATA_DIR']
lemma_dir = paths['LEMMA_DATA_DIR']
ete_dir = paths['ETE_DATA_DIR']
wordvec_dir = paths['WORDVEC_DIR']... |
def bit_width_of(value):
for i in range(0, 64):
if (value == 0):
return i
value >>= 1 |
def select_primitives(primitive_parse):
assert isinstance(primitive_parse, PrimitiveParse)
if (len(primitive_parse.primitives) == 0):
logging.error('No primitive detected.')
return primitive_parse
pixels_dict = _get_pixels_dict(primitive_parse, params.LINE_EPS, params.CIRCLE_EPS)
selecte... |
def save_checkpoint(state, save, epoch):
if (not os.path.exists(save)):
os.makedirs(save)
filename = os.path.join(save, ('checkpt-%04d.pth' % epoch))
torch.save(state, filename) |
def build_many(target, args, processes=None):
from multiprocessing import Process, Queue, cpu_count, set_start_method
if (os.uname().sysname == 'Darwin'):
set_start_method('fork', force=True)
from queue import Empty
if (processes is None):
processes = cpu_count()
workers = ([None] * ... |
class FileRequired(DataRequired):
def __call__(self, form, field):
if (not (isinstance(field.data, FileStorage) and field.data)):
raise StopValidation((self.message or field.gettext('This field is required.'))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.