code stringlengths 101 5.91M |
|---|
class Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
def _set_init_defaults(self, init_type, kwargs):
defaults = {'normal_': {'mean': 0.0, 'std': 0.2}, 'xavier_normal_': {'gain': 0.2}, 'xavier_uniform_': {'gain': 1.0}, 'kaiming_normal_': {'a': 0.0, 'mode': 'f... |
class EvalHistory(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _EVALHISTORY |
def clean_pl_pesel(df: Union[(pd.DataFrame, dd.DataFrame)], column: str, output_format: str='standard', inplace: bool=False, errors: str='coerce', progress: bool=True) -> pd.DataFrame:
if (output_format not in {'compact', 'standard', 'birthdate', 'gender'}):
raise ValueError(f'output_format {output_format} ... |
.parametrize('dtype,device', product(grad_dtypes, devices))
def test_radius_graph(dtype, device):
x = tensor([[(- 1), (- 1)], [(- 1), (+ 1)], [(+ 1), (+ 1)], [(+ 1), (- 1)]], dtype, device)
edge_index = radius_graph(x, r=2.5, flow='target_to_source')
assert (to_set(edge_index) == set([(0, 1), (0, 3), (1, 0)... |
class TestDB(unittest.TestCase):
def testPicklable(self):
s = schema.Struct(('field1', schema.Scalar(dtype=np.int32)), ('field2', schema.List(schema.Scalar(dtype=str))))
s2 = pickle.loads(pickle.dumps(s))
for r in (s, s2):
self.assertTrue(isinstance(r.field1, schema.Scalar))
... |
class GoogleMapSearchAddressBook(VirtualFunctionTool):
name = 'GoogleMapSearchAddressBook'
summary = 'Search for locations in the address book.'
parameters: List[ArgParameter] = [{'name': 'keywords', 'type': 'string', 'description': 'The keywords to search for locations in the address book.', 'required': Tr... |
class TestThresholdSelection(unittest.TestCase):
def test_no_clipping_function(self):
x = np.random.randn(10, 10, 10)
dummy = 0
ml = power_of_two_selection_tensor(x, dummy, n_bits=8, quant_error_method=qc.QuantizationErrorMethod.NOCLIPPING)[THRESHOLD]
self.assertTrue((ml > np.max(np.... |
class Encoder(nn.Module):
def __init__(self, nc, ndf, hidden_size):
super(Encoder, self).__init__()
self.conv1 = nn.Sequential(nn.Conv2d(nc, ndf, kernel_size=3, stride=1, padding=1), nn.ELU(True))
self.conv2 = conv_block(ndf, ndf)
self.conv3 = conv_block(ndf, (ndf * 2))
self.... |
class CustomModel(torch.nn.Module):
def __init__(self, embedding_dim=128, rnn_size=256, layers=2, output_dim=1000, return_hidden=False):
super().__init__()
self.return_hidden = return_hidden
self.reshape = False
self.embedding = sb.nnet.embedding.Embedding(num_embeddings=output_dim, ... |
class XLMWithLMHeadModel():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
def train(model, optimizer, data):
model.train()
optimizer.zero_grad()
out = model(data)
loss = F.nll_loss(out[data.train_mask], data.y[data.train_mask])
loss.backward()
optimizer.step() |
class LibFuzzerModel(BaseModel):
seed = peewee.CharField()
output = peewee.CharField()
group = peewee.CharField()
program = peewee.CharField()
argument = peewee.CharField()
thread = peewee.IntegerField()
pid = peewee.IntegerField() |
class Edge(object):
def __init__(self, source_node: BaseNode, sink_node: BaseNode, source_index: int, sink_index: int):
self.source_node = source_node
self.sink_node = sink_node
self.source_index = source_index
self.sink_index = sink_index
def get_attributes(self) -> Dict[(str, A... |
class sCW_sBC_reg(atomic_reg):
OP_NAME = 'sCW&sBC'
_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_res0_prec', ctypes.c_uint64, 3), (... |
class ExponentialMovingAverage(InvertibleTransformBase):
def __init__(self, alpha: float, normalize: bool=True, p: float=0.95, ci: bool=False):
super().__init__()
self.alpha = alpha
self.normalize = normalize
self.p = p
self.ci = ci
def requires_inversion_state(self):
... |
def compute_md5(cfg: dict) -> str:
md5 = hashlib.md5(json.dumps(cfg, sort_keys=True).encode('utf-8')).hexdigest()
return md5 |
class TFOPTModel(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
class TokenClassificationTask():
def read_examples_from_file(data_dir, mode: Union[(Split, str)]) -> List[InputExample]:
raise NotImplementedError
def get_labels(path: str) -> List[str]:
raise NotImplementedError
def convert_examples_to_features(examples: List[InputExample], label_list: List... |
def calc_gap(theta_true, theta_pred, simplify=True):
gap = (theta_true - theta_pred)
if simplify:
gap = gap.simplify()
return gap |
def set_emotion_in_speaker(emotion_ids, input_ids, bos, eos, speaker1, speaker2, pad):
special_token_ids_list = [bos, eos, speaker1, speaker2]
new_emotion_ids = []
for (i, emotion) in enumerate(emotion_ids):
if (input_ids[i] in special_token_ids_list):
new_emotion_ids.append(emotion_ids[... |
class Scale(Transform):
def __init__(self, scale_factor, output_sz=None, shift=None):
super().__init__(output_sz, shift)
self.scale_factor = scale_factor
def __call__(self, image):
if isinstance(image, torch.Tensor):
(h_orig, w_orig) = image.shape[2:]
if (h_orig !... |
def register_Ns3IntToType__5_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::IntToType< 5 > const &', 'arg0')])
return |
class LoopEntryTransform(Transform, abc.ABC):
def __init__(self, loop_axis=None, entries=()) -> None:
super().__init__()
self.loop_axis = loop_axis
self.entries = entries
def loop_entries(sample: dict, fn, entries, loop_axis=None):
for entry in entries:
if (entry not ... |
_interact(title=(lambda : text_control('<h2>Derivative grapher</h2>')), function=(lambda : input_box(default='x^5-3*x^3+1', label='Function:')), x_range=(lambda : range_slider((- 15), 15, 0.1, default=((- 2), 2), label='Range (x)')), y_range=(lambda : range_slider((- 15), 15, 0.1, default=((- 8), 6), label='Range (y)')... |
def _roundtrip_compare_gpt2_checkpoint(model_id, revision, config: Optional[Gpt2Config]=None):
import torch
converter = Gpt2Config.default_hf_checkpoint_converter
torch_model: HfGpt2LMHeadModel = AutoModelForCausalLM.from_pretrained(model_id, revision=revision)
torch_model.eval()
model: Gpt2LMHeadMo... |
class LabelingFunction():
def __init__(self, name: str, f: Callable[(..., int)], resources: Optional[Mapping[(str, Any)]]=None, pre: Optional[List[BasePreprocessor]]=None) -> None:
self.name = name
self._f = f
self._resources = (resources or {})
self._pre = (pre or [])
def _prepr... |
class _DataListMixin():
def decode_rows(self, stream, conversors):
return list(super().decode_rows(stream, conversors)) |
class Distribution(TorchDistribution):
def sample_and_logprob(self):
s = self.sample()
log_p = self.log_prob(s)
return (s, log_p)
def rsample_and_logprob(self):
s = self.rsample()
log_p = self.log_prob(s)
return (s, log_p)
def mle_estimate(self):
retur... |
def test_wrong_split_strategy() -> None:
with pytest.raises(ValueError, match='Please provide a valid*'):
check_split_strategy(strategy='not_valid') |
class Follower():
def __init__(self, uav_type, uav_id, uav_num):
self.hover = 'HOVER'
self.uav_type = uav_type
self.uav_num = uav_num
self.id = uav_id
self.f = 30
self.pose = PoseStamped()
self.cmd_vel_enu = Twist()
self.avoid_vel = Vector3()
s... |
class RandomRotation(object):
def __init__(self, degrees, resample=False, expand=False, center=None, fill=0):
if isinstance(degrees, numbers.Number):
if (degrees < 0):
raise ValueError('If degrees is a single number, it must be positive.')
self.degrees = ((- degrees),... |
def overview(target, data):
target.write(data['name'])
target.write('\n')
target.write('\n\n')
target.write('\n'.join(data['description']))
target.write('\n\n')
if ('more_info' in data):
target.write('\n'.join(data['more_info']))
target.write('\n\n')
if ('perf_fields' in data... |
def _set_jit_function_cache(key, value):
assert isinstance(value, torch.jit.ScriptFunction)
_jit_caching_layer[key] = value.qualified_name |
def mk_auto_soundness_theorem_block(lean_gen: LeanSoundnessGen, ctx: LeanGenContext) -> Tuple[(Optional[LeanGenContext], Optional[LeanGenContext], Optional[LeanBranchCond])]:
cond: Optional[LeanBranchCond] = None
ctx_pos: Optional[LeanGenContext] = ctx
ctx_neg: Optional[LeanGenContext] = None
while (ctx... |
class SquadFeatures():
def __init__(self, input_ids, attention_mask, token_type_ids, cls_index, p_mask, example_index, unique_id, paragraph_len, token_is_max_context, tokens, token_to_orig_map, start_position, end_position, is_impossible, qas_id: str=None):
self.input_ids = input_ids
self.attention_... |
class EncoderFeedForward(torch.nn.Module):
def __init__(self, num_features, dim, num_gc_layers, num_fc_layers, out_features, dropout):
super(EncoderFeedForward, self).__init__()
self.encoder = Encoder(num_features, dim, num_gc_layers)
input_size_to_feed_forward = (dim * num_gc_layers)
... |
def get_header_dirs():
dirs = [pkg_resources.resource_filename(__name__, 'lib/include')]
return dirs |
def load_results(datafile):
with open(datafile, 'rb') as f:
results = pickle.load(f)
results = [{'search_results': x['search_results'], 'baseline_results': x['baseline_results'], 'bins': x['bins'], 'p_norm': x['p_norm'], 'q_norm': x['q_norm'], 'epsilon': x['epsilon']} for x in results]
retur... |
class GenericPairLoss(BaseMetricLossFunction):
def __init__(self, mat_based_loss, **kwargs):
super().__init__(**kwargs)
self.loss_method = (self.mat_based_loss if mat_based_loss else self.pair_based_loss)
def compute_loss(self, embeddings, labels, indices_tuple):
indices_tuple = lmu.conv... |
class MountainCar(Environment):
def __init__(self):
self.name = MOUNTAINCAR
self.min_position = (- 1.2)
self.max_position = 0.6
self.max_speed = 0.07
self.goal_position = 0.5
self.state = None
self.observation = None
self.n_max_steps = 10000
se... |
def get_heideltime_corpus_stats(heideltime_file: str) -> None:
type_dist = {'DATE': 0, 'SET': 0, 'DURATION': 0, 'TIME': 0}
all_num_sentences = []
all_num_annotations = []
with open(heideltime_file) as f:
json_lines = f.readlines()
prev_id = json.loads(json_lines[0].strip('\n '))['id']
nu... |
def convert_to_coco_json(dataset_name, output_file, allow_cached=True):
PathManager.mkdirs(os.path.dirname(output_file))
with file_lock(output_file):
if (PathManager.exists(output_file) and allow_cached):
logger.warning(f"Using previously cached COCO format annotations at '{output_file}'. Yo... |
def param_name_dict():
layer = caffe_pb2.LayerParameter()
param_names = [s for s in dir(layer) if s.endswith('_param')]
param_type_names = [type(getattr(layer, s)).__name__ for s in param_names]
param_names = [s[:(- len('_param'))] for s in param_names]
param_type_names = [s[:(- len('Parameter'))] f... |
def simple_backward_setup(output, seed=None):
assert isinstance(output, torch.Tensor)
if seed:
torch.manual_seed(seed)
grad_output = torch.randn_like(output)
return (output, grad_output) |
def adjust_learning_rate(optimizer, epoch, config):
if (epoch < config.training.warmup_epochs):
lr = ((config.optim.lr * epoch) / config.training.warmup_epochs)
else:
lr = (config.optim.min_lr + (((config.optim.lr - config.optim.min_lr) * 0.5) * (1.0 + math.cos(((math.pi * (epoch - config.traini... |
def main(parsed_args, **unused_kwargs):
assert (parsed_args.path is not None), '--path required for evaluation!'
if (torch.cuda.is_available() and (not parsed_args.cpu)):
torch.cuda.set_device(parsed_args.device_id)
utils.import_user_module(parsed_args)
logger.info(parsed_args)
use_cuda = (t... |
class CustomDatasetDataLoader(BaseDataLoader):
def name(self):
return 'CustomDatasetDataLoader'
def initialize(self, opt):
BaseDataLoader.initialize(self, opt)
self.dataset = CreateDataset(opt)
self.dataloader = torch.utils.data.DataLoader(self.dataset, batch_size=opt.batchSize, ... |
def save_sample_to_jsonl_gz(function, out_file):
writer = codecs.getwriter('utf-8')
writer(out_file).write(json.dumps(function))
writer(out_file).write('\n') |
class StringListPropertyField(fields.TextAreaField):
def _value(self):
if self.raw_data:
return self.raw_data[0]
else:
return ((self.data and text_type('\n'.join(self.data))) or '')
def process_formdata(self, valuelist):
if valuelist:
try:
... |
def BCPy(JDUTC, ra=0.0, dec=0.0, epoch=2451545.0, pmra=0.0, pmdec=0.0, px=0.0, rv=0.0, zmeas=0.0, loc=None, ephemeris='de430', leap_dir=os.path.join(os.path.dirname(__file__), 'data'), leap_update=True, predictive=False):
(JDTDB, JDTT, warning, error) = utc_tdb.JDUTC_to_JDTDB(JDUTC)
(r_pint, v_pint) = PINT.gcrs... |
class AnswerSelector(object):
def __init__(self, strategy: str):
if (strategy not in STRATEGIES):
raise Exception(f'Unknown strategy: {strategy}')
self.strategy = strategy
self.nlp = spacy.load('en_core_web_sm')
def _get_np_chunks_answers(self, sentence: Span) -> List[AnswerO... |
_module()
class AOTEncoderDecoder(GLEncoderDecoder):
def __init__(self, encoder=dict(type='AOTEncoder'), decoder=dict(type='AOTDecoder'), dilation_neck=dict(type='AOTBlockNeck')):
super().__init__()
self.encoder = build_component(encoder)
self.decoder = build_component(decoder)
self.... |
def main(args) -> None:
save_dir = f'exp/{args.probe_type}/{args.eval_dataset}/{args.framework}_{args.text_type}_{args.text_rep}/'
save_hparams(args, save_dir)
embs_dir = f'{args.msu_dir}/{args.eval_dataset}/pretrained/{args.framework}_{args.text_type}_{args.text_rep}'
if (args.eval_dataset in ['mtg_top... |
def test_RegularArray():
v2_array = ak.highlevel.Array(np.array([[0.0, 1.1, 2.2, 3.3], [4.4, 5.5, 6.6, 7.7]])).layout
assert (to_list(ak._do.combinations(v2_array, 2, replacement=False)) == [[(0.0, 1.1), (0.0, 2.2), (0.0, 3.3), (1.1, 2.2), (1.1, 3.3), (2.2, 3.3)], [(4.4, 5.5), (4.4, 6.6), (4.4, 7.7), (5.5, 6.6)... |
def expected_speedup_compared_to_seq(pipe_times, seq_times: ProfileResult):
def extract_seq_stuff(seq_times):
nocomm_real_b_times = seq_times.nocommb_times_mean
nocomm_real_f_times = seq_times.nocommf_times_mean
real_b_times = seq_times.b_times_mean
real_f_times = seq_times.f_times_m... |
.parametrize('exponent_bits', [5, 6, 7, 8])
_utils.test(require=ti.extension.quant)
def test_shared_exponent_borrow(exponent_bits):
qflt1 = ti.types.quant.float(exp=exponent_bits, frac=10, signed=False)
qflt2 = ti.types.quant.float(exp=exponent_bits, frac=14, signed=False)
a = ti.field(dtype=qflt1)
b = ... |
class PoolFormer(nn.Module):
def __init__(self, model_name: str='S24') -> None:
super().__init__()
assert (model_name in poolformer_settings.keys()), f'PoolFormer model name should be in {list(poolformer_settings.keys())}'
(layers, embed_dims, drop_path_rate) = poolformer_settings[model_name... |
def fused_batch_normalization_backward_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes, axes=(1,), decay_rate=0.9, eps=1e-05, batch_stat=True, nonlinearity='relu'):
is_add = (True if (len(inputs) == 8) else False)
if is_add:
g_dx0 = grad_inputs[0]
g_db0 = grad_inputs[1]
... |
def save_frames_as_video(frames, video_path, fps=30):
(height, width, layers) = frames[0].shape
video = cv2.VideoWriter(video_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (width, height))
for frame in frames:
video.write(cv2.cvtColor((frame * 255).astype(np.uint8), cv2.COLOR_RGB2BGR))
cv2.destroy... |
class DetrForSegmentation():
def __init__(self, *args, **kwargs):
requires_backends(self, ['timm'])
def from_pretrained(cls, *args, **kwargs):
requires_backends(cls, ['timm']) |
def get_backend():
backend = getattr(g, '_backend', None)
if (backend is None):
g._backend = Backend(app.config['user_params'], app.config['schema'], app.config['scenario_db'], app.config['systems'], app.config['sessions'], app.config['controller_map'], app.config['pairing_probabilities'], app.config['n... |
def post_process_generate_ids(tokenizer: PreTrainedTokenizer, ids: torch.Tensor):
ids = copy.deepcopy(ids)
ids[(ids < 0)] = tokenizer.pad_token_id
return ids |
def quadratic_L_function__exact(n, d):
if (n <= 0):
return (QuadraticBernoulliNumber((1 - n), d) / (n - 1))
elif (n >= 1):
if (kronecker_symbol(fundamental_discriminant(d), (- 1)) == 1):
delta = 0
else:
delta = 1
if (((n - delta) % 2) == 0):
fr... |
class NodePrivSAGE(SAGE):
def __init__(self, num_classes, epsilon: Annotated[(float, ArgInfo(help='DP epsilon parameter', option='-e'))], delta: Annotated[(Union[(Literal['auto'], float)], ArgInfo(help='DP delta parameter (if "auto", sets a proper value based on data size)', option='-d'))]='auto', max_degree: Annot... |
def convert_mat(mat_file, in_dir, out_dir):
data = loadmat(osp.join(in_dir, mat_file))
mask = data['GTcls'][0]['Segmentation'][0].astype(np.uint8)
seg_filename = osp.join(out_dir, mat_file.replace('.mat', '.png'))
Image.fromarray(mask).save(seg_filename, 'PNG') |
def iou(det_x, det_y, gt_x, gt_y):
if (approx_area_of_intersection(det_x, det_y, gt_x, gt_y) > 1):
ymax = (np.maximum(np.max(det_y), np.max(gt_y)) + 1)
xmax = (np.maximum(np.max(det_x), np.max(gt_x)) + 1)
bin_mask = np.zeros((ymax, xmax))
det_bin_mask = np.zeros_like(bin_mask)
... |
def assureSingleInstanceName(name):
if (name in name2label):
return name
if (not name.endswith('group')):
return None
name = name[:(- len('group'))]
if (not (name in name2label)):
return None
if (not name2label[name].hasInstances):
return None
return name |
def postprocess_atomic_facts(_atomic_facts, para_breaks, nlp):
verbs = ['born.', ' appointed.', ' characterized.', ' described.', ' known.', ' member.', ' advocate.', 'served.', 'elected.']
permitted_verbs = ['founding member.']
atomic_facts = []
new_atomic_facts = []
new_para_breaks = []
for (i... |
def _preprocess_input(image, footprint=None, out=None, mask=None, out_dtype=None, pixel_size=1):
check_nD(image, 2)
input_dtype = image.dtype
if ((input_dtype in (bool, bool)) or (out_dtype in (bool, bool))):
raise ValueError('dtype cannot be bool.')
if (input_dtype not in (np.uint8, np.uint16))... |
class ExpediaBooking(VirtualFunctionTool):
name = 'ExpediaBooking'
summary = 'Book flight or accommodation options using user-provided details and payment information.'
parameters: List[ArgParameter] = [{'name': 'option_ids', 'type': 'array', 'description': 'An non-empty array of unique identifiers of the o... |
def format_rows(data, metas, sharded_meta=False, headers=['shard_name', 'filename', 'id', 'segment']):
data_with_metas = {}
keys = []
no_meta = 0
for row in data:
fname = Path(row['filename']).stem
flag = False
if sharded_meta:
shard_name = row['shard_name']
... |
def main():
matplotlib.use('Agg')
np.random.seed(args['SEED'])
torch.manual_seed(args['SEED'])
gpuAvailable = torch.cuda.is_available()
device = torch.device(('cuda' if gpuAvailable else 'cpu'))
kwargs = ({'num_workers': args['NUM_WORKERS'], 'pin_memory': True} if gpuAvailable else {})
torch... |
def test_comparison_with_keywords():
p = sqlparse.parse('foo = NULL')[0]
assert (len(p.tokens) == 1)
assert isinstance(p.tokens[0], sql.Comparison)
assert (len(p.tokens[0].tokens) == 5)
assert (p.tokens[0].left.value == 'foo')
assert (p.tokens[0].right.value == 'NULL')
p = sqlparse.parse('fo... |
def evaluate_RWords(continuations, unigramDist):
all_results = []
for continuation in tqdm(continuations):
mean_log_unigram_prob_gold = 0.0
l_gold = 0
for candidate in continuation:
for c in word_tokenize(candidate):
l_gold += 1
if (c in unigra... |
class _LazyAutoMapping(OrderedDict):
def __init__(self, config_mapping, model_mapping):
self._config_mapping = config_mapping
self._reverse_config_mapping = {v: k for (k, v) in config_mapping.items()}
self._model_mapping = model_mapping
self._extra_content = {}
self._modules ... |
class GenerationDataset(Dataset):
def __init__(self, data: List[dict], config: ModelConfigBase=None, training: bool=True):
super().__init__(data, config=config, training=training)
if training:
self._indexing = [(src_idx, trg_idx) for (src_idx, entry) in enumerate(self.data) for (trg_idx,... |
class SawyerDialTurnEnvV2(SawyerXYZEnv):
def __init__(self):
hand_low = ((- 0.5), 0.4, 0.05)
hand_high = (0.5, 1, 0.5)
obj_low = ((- 0.1), 0.7, 0.0)
obj_high = (0.1, 0.8, 0.0)
goal_low = ((- 0.1), 0.73, 0.0299)
goal_high = (0.1, 0.83, 0.0301)
super().__init__(... |
def parse_args(args=None, namespace=None):
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--root_audio', type=pathlib.Path, help='root for extracted audio files')
parser.add_argument('-f', '--root_frame', type=pathlib.Path, help='root for extracted video frames')
parser.add_argument('-o',... |
def parse_args(args=None):
parser = argparse.ArgumentParser(description='Training and Testing Knowledge Graph Embedding Models', usage='train.py [<args>] [-h | --help]')
parser.add_argument('--cuda', action='store_true', help='use GPU')
parser.add_argument('--do_train', action='store_true')
parser.add_a... |
def write_scene_list_html(output_html_filename, scene_list, cut_list=None, css=None, css_class='mytable', image_filenames=None, image_width=None, image_height=None):
if (not css):
css = '\n table.mytable {\n font-family: times;\n font-size:12px;\n color:#000000;\n ... |
class LimitValuation_generic(DiscretePseudoValuation):
def __init__(self, parent, approximation):
DiscretePseudoValuation.__init__(self, parent)
self._initial_approximation = approximation
self._approximation = approximation
def reduce(self, f, check=True):
f = self.domain().coer... |
class CrossNERDataset(CQA):
is_classification = True
def __init__(self, data, *, make_example, **kwargs):
subsample = kwargs.pop('subsample')
domain = kwargs.pop('domain')
examples = []
(example_id, tokens, labels) = (0, [], [])
for (i, line) in enumerate(data):
... |
def train(model, data_loader, optimizer, tokenizer, epoch, warmup_epochs, device, scheduler, config):
model.train()
metric_logger = utils.MetricLogger(delimiter=' ')
metric_logger.add_meter('lr', utils.SmoothedValue(window_size=50, fmt='{value:.8f}'))
metric_logger.add_meter('loss', utils.SmoothedValue... |
def __add_emit_without_colors(fn):
def __emit_without_color(*args):
args[0].levelcolor = ''
args[0].resetcolor = ''
return fn(*args)
return __emit_without_color |
def dump_tensorboard_summary(graph_executor, logdir):
with FileWriter(logdir) as w:
pb_graph = visualize(graph_executor)
evt = event_pb2.Event(wall_time=time.time(), graph_def=pb_graph.SerializeToString())
w.add_event(evt) |
def build_arg(parser):
parser.add_argument('--config', default='config/crnn_mrn.py', help='path to validation dataset')
parser.add_argument('--valid_datas', default=[' ../dataset/MLT17_IL/test_2017', '../dataset/MLT19_IL/test_2019'], help='path to testing dataset')
parser.add_argument('--select_data', type=... |
def test_orchid():
tree = ET.ElementTree(ET.fromstring(SMALL_DOC))
documents = parse_xml(tree)
check_results(documents, EXPECTED_RESULTS, EXPECTED_TEXT, EXPECTED_LABELS) |
class SmoothedValue(object):
def __init__(self, window_size=20, fmt=None):
if (fmt is None):
fmt = '{median:.4f} ({global_avg:.4f})'
self.deque = deque(maxlen=window_size)
self.total = 0.0
self.count = 0
self.fmt = fmt
def update(self, value, n=1):
sel... |
class Classifier(nn.Module):
def __init__(self, in_channels, num_anchors, num_classes, num_layers, pyramid_levels=5, onnx_export=False):
super(Classifier, self).__init__()
self.num_anchors = num_anchors
self.num_classes = num_classes
self.num_layers = num_layers
self.conv_lis... |
def compute_metrics(eval_preds):
(logits, labels) = eval_preds
predictions = np.argmax(logits, axis=(- 1))
return metric.compute(predictions=predictions, references=labels, average='weighted') |
class IMEXRK443(PDEIMEXRK):
def steps(cls):
return 4
def stages(self):
a = np.array([[0, 0, 0, 0, 0], [0, (1 / 2), 0, 0, 0], [0, (1 / 6), (1 / 2), 0, 0], [0, ((- 1) / 2), (1 / 2), (1 / 2), 0], [0, (3 / 2), ((- 3) / 2), (1 / 2), (1 / 2)]])
b = np.array([[0, 0, 0, 0, 0], [(1 / 2), 0, 0, 0,... |
def PrintBytearray(host_workspace):
uint_str = None
prefix = None
print('uint32_t host_workspace[] = {')
for (idx, byte) in enumerate(host_workspace):
if (not (idx % 4)):
if (uint_str is not None):
print(prefix, uint_str, ',')
prefix = ('/* offset: %d B */... |
def define_node(args, node_index, level, parent_index, tree_struct, identity=False):
num_transforms = (0 if (node_index == 0) else count_number_transforms(parent_index, tree_struct))
meta = {'index': node_index, 'parent': parent_index, 'left_child': 0, 'right_child': 0, 'level': level, 'extended': False, 'split... |
def heegner_point_height(self, D, prec=2, check_rank=True):
if (not self.satisfies_heegner_hypothesis(D)):
raise ArithmeticError(('Discriminant (=%s) must be a fundamental discriminant that satisfies the Heegner hypothesis.' % D))
if (check_rank and (self.rank() >= 2)):
return ZZ(0)
if ((D =... |
class SkewPolynomialRing_finite_order(SkewPolynomialRing):
def __init__(self, base_ring, morphism, derivation, name, sparse, category=None):
if (self.Element is None):
import sage.rings.polynomial.skew_polynomial_finite_order
self.Element = sage.rings.polynomial.skew_polynomial_finit... |
def get_bias_by_neighbors(model, v, gender_direction, topn):
neighbors = model.similar_by_vector(v, topn=topn)
neighbors_words = [n for (n, _) in neighbors]
bias = len([n for n in neighbors_words if (model.cosine_similarities(model[n], [gender_direction])[0] > 0)])
bias /= (1.0 * topn)
return bias |
def _mpool(inpOp, kH, kW, dH, dW):
global pool_counter
global parameters
name = ('pool' + str(pool_counter))
pool_counter += 1
if (FLAGS.data_format == 'NCHW'):
ksize = [1, 1, kH, kW]
strides = [1, 1, dH, dW]
else:
ksize = [1, kH, kW, 1]
strides = [1, dH, dW, 1]
... |
class CategoricalMLPModuleEx(nn.Module):
def __init__(self, input_dim, output_dim, hidden_sizes=(32, 32), hidden_nonlinearity=torch.tanh, hidden_w_init=nn.init.xavier_uniform_, hidden_b_init=nn.init.zeros_, output_nonlinearity=None, output_w_init=nn.init.xavier_uniform_, output_b_init=nn.init.zeros_, layer_normaliz... |
class ComponentsTest(unittest.TestCase):
def test_components(self):
g = Graph(num_nodes=12)
g.add_arc(1, 2)
g.add_arc(3, 4)
g.add_arc(5, 6).add_arc(6, 7).add_arc(7, 5)
g.add_arc(8, 9).add_arc(8, 10).add_arc(8, 11)
self.assertEqual(num_components(g), 5)
comps =... |
def dataio_prepare(hparams):
.data_pipeline.takes('path')
.data_pipeline.provides('sig')
def audio_pipeline(wav):
sig = sb.dataio.dataio.read_audio(wav)
return sig
.data_pipeline.takes('path')
.data_pipeline.provides('sig')
def sp_audio_pipeline(wav):
sig = sb.dataio.data... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.