code stringlengths 101 5.91M |
|---|
class Optimizer(abc.ABC):
def step(self, gradients: Dict[(str, ndarray)]) -> None:
pass
def _set_params_from_model(self, model_interface):
class_name = splitext(model_interface.framework_plugin)[1].strip('.')
module_path = splitext(model_interface.framework_plugin)[0]
framework_a... |
()
('--images', 'image_path', help='Path to the images', metavar='PATH|ZIP', type=str, required=True)
('--ref', 'ref_path', help='Dataset reference statistics ', metavar='NPZ|URL', type=str, required=True)
('--num', 'num_expected', help='Number of images to use', metavar='INT', type=click.IntRange(min=2), default=50000... |
def _compare_gpt2_checkpoint_gradients(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 = cast(Gpt2LM... |
class KirillovReshetikhinCrystalFromPromotion(KirillovReshetikhinGenericCrystal, AffineCrystalFromClassicalAndPromotion):
def __init__(self, cartan_type, r, s):
KirillovReshetikhinGenericCrystal.__init__(self, cartan_type, r, s)
AffineCrystalFromClassicalAndPromotion.__init__(self, cartan_type, self... |
class TestRelationNetsCanProcessSupportSetFolder():
.parametrize('support_set_path', ['easyfsl/tests/datasets/resources/balanced_support_set', 'easyfsl/tests/datasets/resources/unbalanced_support_set'])
def test_relation_nets_can_process_support_set_from_balanced_folder(support_set_path):
support_set = ... |
.pure
def test_parse_forward_simple(gpu):
torch_module = copy_to_gpu(gpu, torch.nn.Sequential(torch.nn.Linear(12, 24), torch.nn.Linear(24, 2)))
dace_module = DaceModule(torch_module)
x = copy_to_gpu(gpu, torch.randn(2, 12))
expected = torch_module(x)
result = dace_module(x)
torch_tensors_close('... |
_args('v', 'i', 'i')
def transpose(g, self, dim0, dim1):
if (dim0 == dim1):
return self
if self.isCompleteTensor():
axes = list(range(self.type().dim()))
(axes[dim0], axes[dim1]) = (axes[dim1], axes[dim0])
return g.op('Transpose', self, perm_i=axes)
elif (sym_help._operator_e... |
class TrackObjective(Callback):
def __init__(self):
self.edge_records = []
self.node_records = []
self.model_records = []
def __call__(self, algo, i, max_iter):
if (i == 0):
self.records = []
algo.update_objective()
model_record = dict(A=algo.A_model, ... |
def orient_circuit(circuit, convex=False, precision=53, verbose=False):
vectors = [(v[1].vector() - v[0].vector()) for v in circuit]
circuit_vertex = ((circuit[0][0],) + tuple((e[1] for e in circuit)))
circuit_vertex = tuple(circuit_vertex)
if convex:
pr = matrix([vectors[0], vectors[1]]).determ... |
def compute_predicted_aligned_error(logits: torch.Tensor, max_bin: int=31, no_bins: int=64, **kwargs) -> Dict[(str, torch.Tensor)]:
boundaries = torch.linspace(0, max_bin, steps=(no_bins - 1), device=logits.device)
aligned_confidence_probs = torch.nn.functional.softmax(logits, dim=(- 1))
(predicted_aligned_... |
def test_string():
filename = os.path.join(SAMPLES_DIR, 'string_test_data.avro')
data = ['Hello', 'what', 'should', 'we', 'do', 'for', 'this', 'period', 'of', 'time']
assert (ak.from_avro_file(file=filename).to_list() == data) |
class C(nn.Module):
def __init__(self, nIn, nOut, kSize, stride=1):
super().__init__()
padding = int(((kSize - 1) / 2))
self.conv = nn.Conv2d(nIn, nOut, kSize, stride=stride, padding=padding, bias=False)
def forward(self, input):
output = self.conv(input)
return output |
class RCNNLogLossMetric(BufferedEvalMetric):
def __init__(self):
super(RCNNLogLossMetric, self).__init__('RCNNLogLoss')
self.e2e = config.TRAIN.END2END
(self.pred, self.label) = get_rcnn_names()
def update(self, labels, preds):
pred = preds[self.pred.index('rcnn_cls_prob')]
... |
class Fold(Module):
def __init__(self, output_size, kernel_size, dilation=1, padding=0, stride=1):
super(Fold, self).__init__()
self.output_size = output_size
self.kernel_size = kernel_size
self.dilation = dilation
self.padding = padding
self.stride = stride
def f... |
def send_geth_rpc(url, method, params):
myobj = {'jsonrpc': '2.0', 'id': 1}
myobj['method'] = method
myobj['params'] = params
x = requests.post(url, json=myobj)
y = json.loads(x.text)
return y['result'] |
def neighbors_and_flows(flow_list, edge_idx, node_set={}):
n_and_f = []
for (edge, l) in flow_list:
if (edge[edge_idx] in node_set):
n_and_f.append((edge[(1 + edge_idx)], l))
return n_and_f |
def test(epoch, loader, model, criterion, postloader):
t_start = time.time()
model.eval()
with torch.no_grad():
for resolution in FLAGS.resolution_list:
for width_mult in sorted(FLAGS.width_mult_list, reverse=True):
model.apply((lambda m: setattr(m, 'width_mult', width_mu... |
def visualize_depth(depth, cmap=cv2.COLORMAP_JET):
x = depth.cpu().numpy()
x = np.nan_to_num(x)
mi = np.min(x)
ma = np.max(x)
x = ((x - mi) / max((ma - mi), 1e-08))
x = (255 * x).astype(np.uint8)
x_ = Image.fromarray(cv2.applyColorMap(x, cmap))
x_ = T.ToTensor()(x_)
return x_ |
def test_measure_overlap():
def Ann(start, end):
return Annotation('', start, end, [])
ref = Ann(5, 14)
ref2 = Ann(2, 3)
assert_almost_equal(0.0, Measure.measure_overlap({ref: []}, 'max'))
assert_almost_equal(0.0, Measure.measure_overlap({ref: []}, 'sum'))
assert_almost_equal(0.3, Measur... |
def init_dataset(name, *args, **kwargs):
if (name not in __factory.keys()):
raise KeyError('Unknown datasets: {}'.format(name))
return __factory[name](*args, **kwargs) |
class CNN_exp(FNN_exp):
def __init__(self, data_path, param_dict, config):
super().__init__(data_path, param_dict, config)
def load_model(self):
model = CNNNet(dropout=self.param_dict['dropout'], hidden_layers=self.param_dict['hidden_layers'], kernel_size=self.param_dict['kernel_size'], stride=s... |
def write_db_path(orig_path: str, new_db_path: str, table2column2elements: Dict[(str, Dict[(str, List)])], overwrite: bool=False) -> None:
if (os.path.exists(new_db_path) and (not overwrite)):
print('new database already exists.')
return
empty_db_path = init_empty_db_from_orig_(orig_path)
co... |
def RewriteContext():
context = task_spec_pb2.TaskSpec()
with gfile.FastGFile(FLAGS.task_context) as fin:
text_format.Merge(fin.read(), context)
for resource in context.input:
if (resource.creator == StageName()):
del resource.part[:]
part = resource.part.add()
... |
def _init_parser():
global _parser
_parser = ArgumentParser(description='This script runs the SEPP algorithm on an input tree, alignment, fragment file, and RAxML info file.', conflict_handler='resolve')
_parser.add_argument('-v', '--version', action='version', version=('%(prog)s ' + version))
decompGro... |
def tabulate(tabular_data, headers=[], tablefmt='simple', floatfmt='g', numalign='decimal', stralign='left', missingval=''):
(list_of_lists, headers) = _normalize_tabular_data(tabular_data, headers)
plain_text = '\n'.join((['\t'.join(map(_text_type, headers))] + ['\t'.join(map(_text_type, row)) for row in list_... |
class Adafactor(torch.optim.Optimizer):
def __init__(self, params, lr=None, eps=(1e-30, 0.001), clip_threshold=1.0, decay_rate=(- 0.8), beta1=None, weight_decay=0.0, scale_parameter=True, relative_step=True, warmup_init=False):
if ((lr is not None) and relative_step):
raise ValueError('Cannot co... |
class InitLoader(PTInitializingDataLoader):
def __init__(self, data_loader: DataLoader):
super().__init__(data_loader)
self._data_loader_iter: Iterator
def __iter__(self):
self._data_loader_iter = iter(self._data_loader)
return self
def __next__(self) -> Any:
loaded_i... |
class BertLayer(nn.Module):
def __init__(self, config):
super(BertLayer, self).__init__()
self.attention = BertSelfattLayer(config)
self.intermediate = BertIntermediate(config)
self.output = BertOutput(config)
def forward(self, hidden_states, attention_mask):
attention_ou... |
def train(model, data_loader, optimizer, epoch, device, config):
model.train()
metric_logger = utils.MetricLogger(delimiter=' ')
metric_logger.add_meter('lr', utils.SmoothedValue(window_size=50, fmt='{value:.6f}'))
metric_logger.add_meter('loss', utils.SmoothedValue(window_size=50, fmt='{value:.4f}'))
... |
def compile_timeit_template(*, stmt: str, setup: str, global_setup: str) -> TimeitModuleType:
template_path: str = os.path.join(SOURCE_ROOT, 'timeit_template.cpp')
with open(template_path, 'rt') as f:
src: str = f.read()
module = _compile_template(stmt=stmt, setup=setup, global_setup=global_setup, s... |
class DatetimeRole(ColumnRole):
_name = 'Datetime'
def __init__(self, dtype: Dtype=np.datetime64, seasonality: Optional[Sequence[str]]=('y', 'm', 'wd'), base_date: bool=False, date_format: Optional[str]=None, unit: Optional[str]=None, origin: Union[(str, datetime)]='unix', force_input: bool=False, base_feats: b... |
class _DenseBlock(nn.ModuleDict):
_version = 2
def __init__(self, num_layers, num_input_features, bn_size, growth_rate, drop_rate, memory_efficient=False):
super(_DenseBlock, self).__init__()
for i in range(num_layers):
layer = _DenseLayer((num_input_features + (i * growth_rate)), gr... |
class TestSuiteBranchCoverageFunction(TestSuiteCoverageFunction):
def compute_coverage(self, individual) -> float:
results = self._run_test_suite_chromosome(individual)
merged_trace = analyze_results(results)
tracer = self._executor.tracer
return compute_branch_coverage(merged_trace,... |
def serve_command_factory(args: Namespace):
nlp = pipeline(task=args.task, model=(args.model if args.model else None), config=args.config, tokenizer=args.tokenizer, device=args.device)
return ServeCommand(nlp, args.host, args.port, args.workers) |
def async_copy_to(obj, dev, main_stream=None):
if torch.is_tensor(obj):
v = obj.cuda(dev, non_blocking=True)
if (main_stream is not None):
v.data.record_stream(main_stream)
return v
elif isinstance(obj, collections.Mapping):
return {k: async_copy_to(o, dev, main_strea... |
class ZeroBaseline(Baseline):
def __init__(self, env_spec):
pass
def get_param_values(self, **kwargs):
return None
def set_param_values(self, val, **kwargs):
pass
def fit(self, paths):
pass
def predict(self, path):
return np.zeros_like(path['rewards']) |
def create_argument_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--data_root', type=str, default='datasets/COCO')
parser.add_argument('--save_root', type=str, default='datasets/shp2gir_coco')
parser.add_argument('--image_size', type=int, default=256, help='image size')
parser.ad... |
def _glue_convert_examples_to_features(examples: List[InputExample], tokenizer: PreTrainedTokenizer, max_length: Optional[int]=None, task=None, label_list=None, output_mode=None):
if (max_length is None):
max_length = tokenizer.model_max_length
if (task is not None):
processor = glue_processors[... |
def trace(title: str):
t0 = time()
p = psutil.Process(os.getpid())
m0 = (p.memory_info()[0] / (2.0 ** 30))
(yield)
m1 = (p.memory_info()[0] / (2.0 ** 30))
delta = (m1 - m0)
sign = ('+' if (delta >= 0) else '-')
delta = math.fabs(delta)
print(f'[{m1:.1f}GB ({sign}{delta:.3f}GB): {(tim... |
class LeanSpecGenerator():
file_names: LeanFileNames
lean_info: LeanProgramInfo
simplifier: LeanExprSimplifier
spec_file_exists: bool = False
specs: List[str] = dataclasses.field(default_factory=(lambda : []))
func: Optional[LeanFunctionInfo] = None
def main_scope(self) -> ScopedName:
... |
def gen_time_pair():
time_formats = ['am', 'pm', 'standard']
time_format = np.random.choice(time_formats, 1)[0]
if ((time_format == 'am') or (time_format == 'pm')):
hour = random.randint(1, 11)
leave_min = random.randint(10, 29)
arrive_min = (leave_min + random.randint(10, 30))
... |
def _random_stone_lattice(n):
from sage.arith.misc import factor
from sage.combinat.partition import Partitions
from sage.misc.misc_c import prod
from copy import copy
factors = sum([([f[0]] * f[1]) for f in factor(n)], [])
sage.misc.prandom.shuffle(factors)
part_lengths = list(Partitions(le... |
class ClassificationModule(MLPNodeClassifier):
def __init__(self, *, num_channels: int, num_classes: int, hidden_dim: int=16, base_layers: int=2, head_layers: int=1, combination: MultiMLP.CombType='cat', activation_fn: Callable[([Tensor], Tensor)]=torch.relu_, dropout: float=0.0, batch_norm: bool=False):
su... |
class DistributedDataParallel(Module):
def __init__(self, module, device_ids=None, output_device=None, dim=0, broadcast_buffers=True):
super(DistributedDataParallel, self).__init__()
if (dist._backend not in (dist.dist_backend.NCCL, dist.dist_backend.GLOO)):
raise ValueError('Invalid bac... |
class BinaryOpBenchmark(op_bench.TorchBenchmarkBase):
def init(self, M, N, K, device, dtype_one, dtype_two, op_func):
self.input_one = torch.randn(M, N, K, device=device).to(dtype=dtype_one)
self.input_two = torch.randn(M, N, K, device=device).to(dtype=dtype_two)
self.op_func = op_func
d... |
def test_new_style_tuple():
form = {'class': 'RecordArray', 'fields': None, 'contents': [{'class': 'NumpyArray', 'primitive': 'int64', 'inner_shape': [], 'parameters': {}, 'form_key': 'node1'}, {'class': 'NumpyArray', 'primitive': 'int64', 'inner_shape': [], 'parameters': {}, 'form_key': 'node2'}], 'parameters': {}... |
class RandomFourierFeatures(ModelLayer):
def __init__(self, model, input_record, output_dims, sigma, w_init=None, b_init=None, name='random_fourier_features', **kwargs):
super(RandomFourierFeatures, self).__init__(model, name, input_record, **kwargs)
assert isinstance(input_record, schema.Scalar), '... |
.no_cover
.timeout(30)
def test_ppo_memorize_digits():
env = os.environ.copy()
env['GARAGE_EXAMPLE_TEST_N_EPOCHS'] = '1'
command = [str((EXAMPLES_ROOT_DIR / 'tf/ppo_memorize_digits.py')), '--batch_size', '4']
assert (subprocess.run(command, check=False, env=env).returncode == 0) |
_utils.test()
def test_double_for_loops_more_nests():
N = 6
a = ti.field(ti.f32, shape=N, needs_dual=True)
b = ti.field(ti.f32, shape=N, needs_dual=True)
c = ti.field(ti.i32, shape=(N, (N // 2)))
f = ti.field(ti.f32, shape=(N, (N // 2)), needs_dual=True)
def double_for():
for i in range(... |
class ResNet(nn.Module):
def __init__(self, block, layers, used_layers):
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=0, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
sel... |
def convert_datasets_with_entity_mention_annotations(train: List, subj_index_mapper: IndexMapper, obj_index_mapper: IndexMapper, rel_index_mapper: IndexMapper, others_train: List[List]=[], valid_and_test: List[List]=[], triple_format_parser=(lambda x: x.strip().split('\t')), mention_format_parser=(lambda x: [y.strip() ... |
def undo_filter_paeth(filter_unit, scanline, previous, result):
ai = (- filter_unit)
for i in range(len(result)):
x = scanline[i]
if (ai < 0):
a = c = 0
else:
a = result[ai]
c = previous[ai]
b = previous[i]
p = ((a + b) - c)
pa ... |
class UniformActivationNet(torch.nn.Module):
def __init__(self, input_shape):
super(UniformActivationNet, self).__init__()
(_, in_channels, _, _) = input_shape[0]
self.conv1 = torch.nn.Conv2d(in_channels, 3, kernel_size=(3, 3))
self.bn1 = torch.nn.BatchNorm2d(3)
self.conv2 = ... |
def split_auth_from_netloc(netloc):
if ('' not in netloc):
return (netloc, (None, None))
(auth, netloc) = netloc.rsplit('', 1)
if (':' in auth):
user_pass = auth.split(':', 1)
else:
user_pass = (auth, None)
user_pass = tuple(((None if (x is None) else urllib_unquote(x)) for x... |
class TranslationTool(PipelineTool):
default_checkpoint = 'facebook/nllb-200-distilled-600M'
description = "This is a tool that translates text from a language to another. It takes three inputs: `text`, which should be the text to translate, `src_lang`, which should be the language of the text to translate and ... |
class VectorType(MatrixType):
def __init__(self, n, dtype):
super().__init__(n, 1, 1, dtype)
def __call__(self, *args):
if (len(args) == 0):
raise TaichiSyntaxError('Custom type instances need to be created with an initial value.')
if (len(args) == 1):
if (isinsta... |
class ModelArguments():
model_name_or_path: str = field(default=None, metadata={'help': 'Name to a huggingface native pretrained model or path to a model on disk.'}) |
class EntanglementGenerationB(EntanglementProtocol):
def __init__(self, own: 'BSMNode', name: str, others: List[str]):
super().__init__(own, name)
assert (len(others) == 2)
self.others = others
def bsm_update(self, bsm: 'SingleAtomBSM', info: Dict[(str, Any)]):
assert (info['info... |
def _load_unicode_escapes(v, hexbytes, prefix):
skip = False
i = (len(v) - 1)
while ((i > (- 1)) and (v[i] == '\\')):
skip = (not skip)
i -= 1
for hx in hexbytes:
if skip:
skip = False
i = (len(hx) - 1)
while ((i > (- 1)) and (hx[i] == '\\')):
... |
class _MechanicalTurkRequestImporter():
def __init__(self, template: CritiqueTaskTemplate):
self._template: CritiqueTaskTemplate = template
self._request_key_to_results: Dict[(_CritiqueRequestKey, CritiqueRequestResult)] = {}
def _get_directory_path(self):
return os.path.join('mturk', se... |
def test_finish(event_stream):
assert isinstance(next(event_stream), events.Initialized)
event = event_stream.finish()
assert isinstance(event, events.Finished)
assert (next(event_stream, None) is None) |
class GPT2BPETokenizer(Tokenizer):
def __init__(self, cache_dir=None, **kwargs):
self.text_tokenizer = GPT2Tokenizer.from_pretrained('gpt2', cache_dir=cache_dir)
self.text_tokenizer.max_len = int(.0)
self.num_command_tokens = 2
self.num_tokens = len(self.text_tokenizer.encoder)
... |
def test_not_fix_example():
with tempfile.TemporaryDirectory(dir=TEST_WORKING_DIR) as tempdir:
test_name = os.path.join(tempdir, 'nofix.xml')
with open(test_name, 'w', encoding='utf-8') as fout:
fout.write(NOT_FIX_NONPROJ_EXAMPLE)
sentences = convert_arboretum.read_xml_file(test_... |
def rand_saturation(x, param):
ratio = param.saturation
x_mean = x.mean(dim=1, keepdim=True)
set_seed_DiffAug(param)
rands = torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device)
if param.Siamese:
rands[:] = rands[0]
x = (((x - x_mean) * (rands * ratio)) + x_mean)
return x |
class ASR(sb.Brain):
def compute_forward(self, batch, stage):
batch = batch.to(self.device)
(wavs, wav_lens) = batch.sig
(bos_tokens, _) = batch.tokens_bos
if self.hparams.gradient_checkpointing:
wavs.requires_grad_()
(enc_out, logits, _) = torch.utils.checkpo... |
def get_edge_set(g: dgl.DGLGraph):
return set(map(tuple, np.column_stack([_.cpu().numpy() for _ in g.edges()]).tolist())) |
def readspec():
specdict = {}
with open(os.path.join(CURRENT_DIR, '..', 'kernel-specification.yml')) as f:
loadfile = yaml.load(f, Loader=yaml.CSafeLoader)
indspec = loadfile['kernels']
with open(os.path.join(CURRENT_DIR, '..', 'kernel-test-data.json')) as f:
data = json.load(f)['tests']... |
def main(args):
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('destination_dir', help='destination directory')
parser.add_argument('deps', help='file with header file names to parse')
pargs = parser.parse_args(args)
if (not mk_g... |
def cublas_type_metadata(dtype: dtypes.typeclass) -> Tuple[(str, str, str)]:
if (dtype == dtypes.float16):
return ('H', '__half', 'Half')
elif (dtype == dtypes.float32):
return ('S', 'float', 'Float')
elif (dtype == dtypes.float64):
return ('D', 'double', 'Double')
elif (dtype ==... |
def get_net(data_loader, name):
logger = logging.getLogger(__name__)
blob_names = data_loader.get_output_names()
net = core.Net(name)
net.type = 'dag'
for gpu_id in range(cfg.NUM_GPUS):
with core.NameScope('gpu_{}'.format(gpu_id)):
with core.DeviceScope(muji.OnGPU(gpu_id)):
... |
class AggPredictor():
def __init__(self, question, sql, history, kw=None):
self.sql = sql
self.question = question
self.history = history
self.kw = kw
def generate_output(self):
label = (- 1)
if self.kw:
key = self.kw
else:
key = se... |
def get_constant_schedule_with_warmup(optimizer, num_warmup_steps, last_epoch=(- 1)):
def lr_lambda(current_step: int):
if (current_step < num_warmup_steps):
return (float(current_step) / float(max(1.0, num_warmup_steps)))
return 1.0
return LambdaLR(optimizer, lr_lambda, last_epoch=l... |
class LogFriendlyProgressBar():
def __init__(self, iterable, desc, total, step: int=1):
self._desc = desc
self._i = 0
self._N = total
self.step = step
self._progress = 0
self._iterable = iterable
self._iterator = None
def __iter__(self):
self._iter... |
.parametrize('value, expected', (({'key': '1'}, True), ({'key': 1}, True), ({'key': '\udcff'}, False), ({'key': ['1', 'abc', '\udcff']}, False)))
def test_is_valid_query(value, expected):
assert (is_valid_query(value) == expected) |
class Tool(BaseTool):
description: str = ''
func: Callable[([str], str)]
coroutine: Optional[Callable[([str], Awaitable[str])]] = None
max_output_len = 3000
def _run(self, tool_input: str) -> str:
return self.func(tool_input)
async def _arun(self, tool_input: str) -> str:
if self... |
def schema(open_api_3_schema_with_recoverable_errors):
return schemathesis.from_dict(open_api_3_schema_with_recoverable_errors) |
def node_to_internal_type(node: bblfsh.Node):
if (type(node) == str):
return node
return node.internal_type |
_utils.test()
def test_write_after_break():
a = ti.field(ti.i32, shape=5)
a.fill((- 1))
def foo():
ti.loop_config(serialize=True)
for i in range(5):
while True:
if (i > 3):
break
a[i] = i
break
foo()
asse... |
class BasicModel(torch.nn.Module):
def __init__(self):
super(BasicModel, self).__init__()
self.conv1 = Conv2d(8, 8, 3)
self.bn = BatchNorm2d(8)
self.relu = ReLU()
def forward(self, inp):
size = inp.shape
x = self.conv1(inp)
x = self.bn(x)
x = self.... |
def ftimer_handle_frame(exp_meta, exp_meta_lock, frame):
if (len(frame['payload']) < 12):
return
try:
msg = dissect.base.LoRaWANMessage(frame['payload'])
if (msg.mhdr.data_msg and seq_eq(msg.payload.fhdr.devAddr, DUT_DEV_ADDR)):
f_cnt = msg.payload.fhdr.fCnt
port ... |
def test_all_checks():
_test_single_check(BaseBadSampler, check_target_type)
_test_single_check(SamplerSingleClass, check_samplers_one_label)
_test_single_check(NotFittedSampler, check_samplers_fit)
_test_single_check(NoAcceptingSparseSampler, check_samplers_sparse)
_test_single_check(NotPreservingD... |
_python_op()
class ResourceTest(Kernel):
def __init__(self, config, path):
self.path = path
def fetch_resources(self):
with open(self.path, 'r') as f:
n = int(f.read())
with open(self.path, 'w') as f:
f.write(str((n + 1)))
def setup_with_resources(self):
... |
def create_model(metric: str='cosine', scale_cls: int=10.0, learn_scale: bool=True, normalize: bool=True):
return PN_head(metric, scale_cls, learn_scale, normalize) |
def bin_to_ascii(B):
n = len(B)
if (n == 0):
raise ValueError('B must be a non-empty binary string.')
if (mod(n, 8) != 0):
raise ValueError('The number of bits in B must be a multiple of 8.')
b = [int(str(x)) for x in list(B)]
A = []
k = (n // 8)
for i in range(k):
A.... |
def fine_type(mention):
if (mention.attributes['type'] == 'NOM'):
mention_fine_type = mention.attributes['fine_type']
elif (mention.attributes['type'] == 'PRO'):
mention_fine_type = mention.attributes['citation_form']
else:
mention_fine_type = mention.attributes['type']
if (not m... |
def _kind_name(dtype):
try:
return _kind_to_stem[dtype.kind]
except KeyError:
raise RuntimeError('internal dtype error, unknown kind {!r}'.format(dtype.kind)) |
class Optimizer():
def __init__(self, model, sess, ob_batch_num=100):
self.model = model
self.sess = sess
self.ob_batch_num = ob_batch_num
self.scan_data = 0
self.scan_batch = 0
self.ret_loss = 0
self.tb_point = 0
def _reset_optm_info(self):
self.s... |
_method
class UnknownClass(UniqueRepresentation):
def __repr__(self):
return 'Unknown'
def __bool__(self):
raise UnknownError('Unknown does not evaluate in boolean context')
def __and__(self, other):
if (other is False):
return False
elif ((other is True) or (othe... |
_dispatch
def rfft2(x, s=None, axes=((- 2), (- 1)), norm=None, overwrite_x=False, workers=None):
return (Dispatchable(x, np.ndarray),) |
def test_tocuda_unimplementedkernels7():
content = ak.contents.NumpyArray(np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.1]))
offsets = ak.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10]))
listoffsetarray = ak.contents.ListOffsetArray(offsets, content)
content1 = ak.contents.NumpyArray(np... |
class ControlFlowToyModel(nn.Module):
def __init__(self):
super(ControlFlowToyModel, self).__init__()
self.lin1 = nn.Linear(10, 10, bias=False)
self.lin2 = nn.Linear(10, 10, bias=False)
def forward(self, x):
use_second_layer = torch.equal(x, torch.ones(20, 10, device=x.device))
... |
class _decomposition4d_args():
log2_hashmap_size: int = 19
n_features_per_level: int = 2
n_levels: int = 16
coarsest_resolution: int = 32
finest_resolution: int = 2048 |
def get_dataset(args, models, shuffle=False):
(shards_path, rest) = get_shards_path(args, f=get_shards_size)
if isinstance(args.computation.num_gpus, int):
world_size = min(du.get_world_size(), args.computation.num_gpus)
else:
world_size = du.get_world_size()
batch_size = int((args.data.... |
def model_fields(model, only=None, exclude=None, field_args=None, converter=None):
converter = (converter or ModelConverter())
field_args = (field_args or {})
props = model.properties()
sorted_props = sorted(iteritems(props), key=(lambda prop: prop[1].creation_counter))
field_names = list((x[0] for ... |
(frozen=True)
class FunctionSchema():
name: 'OperatorName'
arguments: Sequence['Argument']
kwarg_only_arguments: Sequence['Argument']
out_arguments: Sequence['Argument']
returns: Sequence['Return']
def schema_order_arguments(self) -> Iterator['Argument']:
return itertools.chain(self.argu... |
def deprocess_image(img):
img = (img - np.mean(img))
img = (img / (np.std(img) + 1e-05))
img = (img * 0.1)
img = (img + 0.5)
img = np.clip(img, 0, 1)
return np.uint8((img * 255)) |
class CodeData(torch.utils.data.Dataset):
def __init__(self, cad_path, solid_path, profile_path, loop_path):
with open(cad_path, 'rb') as f:
cad_data = pickle.load(f)
with open(solid_path, 'rb') as f:
solid_data = pickle.load(f)
self.solid_code = solid_data['content']... |
.parametrize('implementation', ['pure', 'im2col'])
.parametrize('num_in_channels, kernel_size, num_filters, bias', [(1, (3, 3), 8, True), (8, (3, 3), 3, False), (8, (5, 5), 3, True), (8, (4, 4), 3, False)])
.pure
def test_conv_simple(num_in_channels, kernel_size, num_filters, bias, implementation):
if (implementati... |
def matrix_interaction_plot(interaction_matrix, tokens, axis=None, cbar_kw=None, cbarlabel='Interaction Value', zero_diagonals=True, **kwargs):
if (cbar_kw is None):
cbar_kw = {}
if zero_diagonals:
interaction_matrix = interaction_matrix.copy()
np.fill_diagonal(interaction_matrix, 0.0)
... |
def generate_contradictory_answer_from_context(document: str, synth_question: str):
time.sleep(1)
for _ in range(5):
try:
system_prompt = 'Create an answer for the given question that contradicts the provided document. You should create false information that disagrees with what exists withi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.