code stringlengths 101 5.91M |
|---|
class QuotientsCategory(RegressiveCovariantConstructionCategory):
_functor_category = 'Quotients'
def default_super_categories(cls, category):
return Category.join([category.Subquotients(), super().default_super_categories(category)]) |
class TestAllFindings():
def setup(self):
self.detector = StubDetector()
self.misuse = create_misuse('-m1-')
self.misuses = [self.misuse, create_misuse('-m2-')]
self.detector_run = MagicMock()
self.detector_run.detector = self.detector
self.uut = AllFindingsFilterTask... |
def _seg_34():
return [(13170, 'M', u'da'), (13171, 'M', u'au'), (13172, 'M', u'bar'), (13173, 'M', u'ov'), (13174, 'M', u'pc'), (13175, 'M', u'dm'), (13176, 'M', u'dm2'), (13177, 'M', u'dm3'), (13178, 'M', u'iu'), (13179, 'M', u''), (13180, 'M', u''), (13181, 'M', u''), (13182, 'M', u''), (13183, 'M', u''), (13184... |
class OpenImagesCfg():
variant: str = None
parser: str = 'openimages'
num_classes: int = None
img_filename = '%s.jpg'
splits: Dict[(str, dict)] = None |
def write_lst(lst, output_file):
out_f = open(output_file, 'w')
print('Writing lines to file...')
out_f.writelines(lst)
out_f.close()
print('Lines written to files') |
class BernoulliTS(BaseContextFreePolicy):
alpha: Optional[np.ndarray] = None
beta: Optional[np.ndarray] = None
is_zozotown_prior: bool = False
campaign: Optional[str] = None
policy_name: str = 'bts'
def __post_init__(self) -> None:
super().__post_init__()
if self.is_zozotown_prio... |
def ComplexIntervalField(prec=53, names=None):
global cache
if (prec in cache):
X = cache[prec]
C = X()
if (C is not None):
return C
C = ComplexIntervalField_class(prec)
cache[prec] = weakref.ref(C)
return C |
def starts_with(anaphor_cleaned_tokens, antecedent_cleaned_tokens):
for (ana_token, ante_token) in zip(anaphor_cleaned_tokens, antecedent_cleaned_tokens):
if (ana_token != ante_token):
return False
return True |
def params_and_buffers(module):
assert isinstance(module, torch.nn.Module)
return (list(module.parameters()) + list(module.buffers())) |
def demo_heuristic_lander(env, w, seed=None):
total_reward = 0
steps = 0
env = wrappers.Monitor(env, './', force=True)
env.reset(seed=seed)
s = env.reset()
while True:
if (steps > STEPS_LIMIT):
total_reward -= TIMEOUT_REWARD
return total_reward
a = heurist... |
def get_display_profile(handle=None):
if (sys.platform != 'win32'):
return None
from PIL import ImageWin
if isinstance(handle, ImageWin.HDC):
profile = core.get_display_profile_win32(handle, 1)
else:
profile = core.get_display_profile_win32((handle or 0))
if (profile is None)... |
class TypeSpec():
_types: Dict[(str, Type)]
def __init__(self):
self._types = dict()
def get_type(self, name: str) -> Optional[Type]:
return self._types.get(name)
def get_type_or_raise(self, name: str) -> Type:
return self._types[name]
def define_type(self, ty: Type) -> Type:... |
class NOPaxosClient(AppConfig):
def __init__(self) -> None:
super().__init__()
self.server_ips: tp.List[str] = []
self.is_last = False
self.use_ehseq = False
def run_cmds(self, node: NodeConfig) -> tp.List[str]:
cmds = []
for ip in self.server_ips:
cmd... |
def create_exp_name(exp_prefix, exp_id=0, seed=0):
now = datetime.datetime.now(dateutil.tz.tzlocal())
timestamp = now.strftime('%Y_%m_%d_%H_%M_%S')
return ('%s_%s_%04d--s-%d' % (exp_prefix, timestamp, exp_id, seed)) |
def configure_gpu(use_gpu: bool, which_gpu: int) -> torch.device:
if use_gpu:
device = torch.device('cuda')
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
os.environ['CUDA_VISIBLE_DEVICES'] = str(which_gpu)
else:
device = torch.device('cpu')
os.environ['CUDA_VISIBLE_DEVIC... |
class TestJsonIO(object):
def test_ace2004(self):
io = JsonIO(text_key='tokens', chunk_key='entities', chunk_type_key='type', chunk_start_key='start', chunk_end_key='end')
train_data = io.read('data/ace-lu2015emnlp/ACE2004/train.json')
dev_data = io.read('data/ace-lu2015emnlp/ACE2004/dev.jso... |
class Inference():
def __init__(self, model: str, checkpoint: str, det_model: str, det_checkpoint: str) -> None:
self.device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))
self.model = eval(model)(112)
self.model.load_state_dict(torch.load(checkpoint, map_location='cpu'), s... |
def register_Ns3MmWaveMacCschedSapUserCschedUeReleaseCnfParameters_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::MmWaveMacCschedSapUser::CschedUeReleaseCnfParameters const &', 'arg0')])
cls.add_instance_attribute('m_result', 'ns3::Result_e', is_const=False)
cls.add_... |
def test_toarrow_NumpyArray_2():
array = ak.contents.NumpyArray(np.array([[0.0, 1.1], [2.2, 3.3], [4.4, 5.5]]))
assert isinstance(array.to_arrow(), pyarrow.lib.Array)
assert (array.to_arrow().to_pylist() == [[0.0, 1.1], [2.2, 3.3], [4.4, 5.5]]) |
def test_get_last_mutatable_statement_max(test_case_chromosome_with_test):
(chromosome, test_case) = test_case_chromosome_with_test
test_case.add_statement(IntPrimitiveStatement(test_case, 5))
assert (chromosome.get_last_mutatable_statement() == 0) |
def add_log_to_file(log_path):
fh = logging.FileHandler(log_path)
formatter = logging.Formatter(_LOG_FMT, datefmt=_DATE_FMT)
fh.setFormatter(formatter)
LOGGER.addHandler(fh) |
class DModel(nn.Module):
def __init__(self, opt):
super(DModel, self).__init__()
self.opt = opt
self.fc = nn.Sequential(nn.Linear(2, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 2))
def forward(self, data):
return self.fc(data) |
def adjust_sigmoid(image, cutoff=0.5, gain=10, inv=False):
_assert_non_negative(image)
dtype = image.dtype.type
scale = float((dtype_limits(image, True)[1] - dtype_limits(image, True)[0]))
if inv:
out = ((1 - (1 / (1 + np.exp((gain * (cutoff - (image / scale))))))) * scale)
return dtype(... |
def resize(in_dict, cfg):
in_dict['img'] = Image.fromarray(cv2.resize(np.array(in_dict['img']), (cfg.width, cfg.height), interpolation=cv2.INTER_LINEAR))
in_dict['mask'] = Image.fromarray(cv2.resize(np.array(in_dict['mask']), (cfg.width_mask, cfg.height_mask), cv2.INTER_NEAREST), mode='L') |
def test_action_space_0():
env = Warehouse(shelf_columns=1, column_height=3, shelf_rows=3, n_agents=2, msg_bits=0, sensor_range=1, request_queue_size=5, max_inactivity_steps=None, max_steps=None, reward_type=RewardType.GLOBAL)
env.reset()
assert (env.action_space == spaces.Tuple((2 * (spaces.Discrete(len(Ac... |
def test_open_api_verbose_name(openapi_30):
assert (openapi_30.verbose_name == 'Open API 3.0.0')
assert (openapi_30.spec_version == '3.0.0') |
def _generate_batch_data(sampler, batch_size):
batch = []
for idx in sampler:
batch.append(idx)
if (len(batch) == batch_size):
(yield batch)
batch = []
if (len(batch) > 0):
(yield batch) |
def _check_pickleable(obj):
def recurse(obj):
if isinstance(obj, (list, tuple, set)):
return [recurse(x) for x in obj]
if isinstance(obj, dict):
return [[recurse(x), recurse(y)] for (x, y) in obj.items()]
if isinstance(obj, (str, int, float, bool, bytes, bytearray)):
... |
def eval_ndcg_at_k(inference_model, device, df_valid, valid_loader, batch_size, k_list, gain_type, phase='Eval'):
ndcg_metrics = {k: NDCG(k, gain_type) for k in k_list}
(qids, rels, scores) = ([], [], [])
inference_model.to_eval()
with torch.no_grad():
for (qid, rel, x) in valid_loader.generate_... |
def GetNodeInDegV_PNGraph(Graph, NIdInDegV):
return _snap.GetNodeInDegV_PNGraph(Graph, NIdInDegV) |
class DataDimLoops(util.ContentHashClass):
def __init__(self, *lpe_list):
for lpe in lpe_list:
if (lpe not in range(le.NUM)):
raise ValueError('DataDimLoops: arguments must be LoopEnum.')
self.lpe_tuple = tuple(sorted(set(lpe_list)))
def loops(self):
return se... |
class Optimizer():
def init_parser(parser: argparse.ArgumentParser):
parser_group = parser.add_argument_group('Optimization')
parser_group.add_argument('-o', '--optimizer', default='Adam', type=str, help="The optimizer class, 'torch.optim.XXX'")
parser_group.add_argument('-lr', default=0.01,... |
def check_tolerance(ftol, xtol, gtol, method):
def check(tol, name):
if (tol is None):
tol = 0
elif (tol < EPS):
warn(f'Setting `{name}` below the machine epsilon ({EPS:.2e}) effectively disables the corresponding termination condition.', stacklevel=3)
return tol
... |
class MapRelativeToAbsoluteNumberField(NumberFieldIsomorphism):
def __init__(self, R, A):
NumberFieldIsomorphism.__init__(self, Hom(R, A))
def _call_(self, x):
A = self.codomain()
f = x.polynomial()
return A._element_class(A, f) |
def get_data_augmentation_with_wikisql_tag(args):
aug_wikisql_tag = ('wikisql.' if args.augment_with_wikisql else '')
return aug_wikisql_tag |
def get_generic_path_information(paths, stat_prefix=''):
statistics = OrderedDict()
returns = [sum(path['rewards']) for path in paths]
rewards = np.vstack([path['rewards'] for path in paths])
if ('q_preds' in paths[0]):
(q_preds, q_trues, q_pred_true_gaps) = get_q_pred_true_gaps(paths)
s... |
def get_just_x_or_y_train_dev_dataset(just, DATA_DIR, **kw):
tokenizer = kw['tokenizer']
task_name = kw['task_name']
max_seq_length = kw['max_seq_length']
overwrite_cache = kw['overwrite_cache']
is_last_partition = kw.get('is_last_partition')
precompute_attention_mask = kw['precompute_attention_... |
def _get_type_candidates(context: MutationContext, schema: Schema) -> set[str]:
types = set(get_type(schema))
if context.is_path_location:
candidates = ({'string', 'integer', 'number', 'boolean', 'null'} - types)
else:
candidates = ({'string', 'integer', 'number', 'object', 'array', 'boolean... |
def agg_dict_list(dict_list):
dict_agg = {'epoch': dict_list[0]['epoch']}
for key in dict_list[0]:
if (key != 'epoch'):
value = np.array([dict[key] for dict in dict_list])
dict_agg[key] = np.mean(value).round(cfg.round)
dict_agg['{}_std'.format(key)] = np.std(value).r... |
class SelfConsciousDialogueTeacher(FixedDialogTeacher):
def __init__(self, opt, shared=None):
super().__init__(opt, shared)
self.opt = opt
(datapath, datatype) = _path(opt)
if (not shared):
self.episodes = []
self.num_exs = 0
self._setup_data(datap... |
def tensor2depth(input_depth, imtype=np.int32):
if isinstance(input_depth, torch.Tensor):
depth_tensor = input_depth.data
else:
return input_depth
depth_numpy = depth_tensor[0].cpu().float().numpy()
depth_numpy = depth_numpy.reshape((depth_numpy.shape[1], depth_numpy.shape[2]))
retur... |
_func
def sample3(qf: ti.types.ndarray(ndim=2), u: int, v: int) -> vec3:
return sample_impl(qf, u, v) |
def run_tests():
read_waf_config()
global BUILD_PROFILE_SUFFIX
if (BUILD_PROFILE == 'release'):
BUILD_PROFILE_SUFFIX = ''
else:
BUILD_PROFILE_SUFFIX = ('-' + BUILD_PROFILE)
test_runner_name = ('%s%s-%s%s' % (APPNAME, VERSION, 'test-runner', BUILD_PROFILE_SUFFIX))
if (not options.... |
def process(passageIDs, response):
output = ''
for i in range(len(passageIDs)):
output += '{}\t'.format(passageIDs[i])
for j in range(len(response[i])):
output += '{} '.format(response[i][j])
output += '\n'
return output |
class ConstructorStatement(ParametrizedStatement):
def clone(self, test_case: tc.TestCase, memo: dict[(vr.VariableReference, vr.VariableReference)]) -> Statement:
return ConstructorStatement(test_case, self.accessible_object(), self._clone_args(memo))
def accept(self, visitor: StatementVisitor) -> None:... |
def res2net101_v1b_26w_4s(pretrained=False, **kwargs):
model = Res2Net(Bottle2neck, [3, 4, 23, 3], baseWidth=26, scale=4, **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['res2net101_v1b_26w_4s']))
return model |
class InvalidSDFGNodeError(InvalidSDFGError):
def __init__(self, message: str, sdfg: 'SDFG', state_id: int, node_id: int):
self.message = message
self.sdfg = sdfg
self.state_id = state_id
self.node_id = node_id
self.path = None
def to_json(self):
return dict(messa... |
class BrokenPicklingConjugateGradientOptimizer(ConjugateGradientOptimizer):
def state(self):
return dict()
def state(self, state):
ConjugateGradientOptimizer.state.fset(self, state) |
_model
def ens_adv_inception_resnet_v2(pretrained=False, num_classes=1000, in_chans=3, **kwargs):
default_cfg = default_cfgs['ens_adv_inception_resnet_v2']
model = InceptionResnetV2(num_classes=num_classes, in_chans=in_chans, **kwargs)
model.default_cfg = default_cfg
if pretrained:
load_pretrain... |
class BackpackGpt2Embeddings(eqx.Module):
Vocab: Axis = eqx.static_field()
config: Gpt2Config = eqx.static_field()
token_embeddings: NamedArray
position_embeddings: NamedArray
dropout: hnn.Dropout
def init(Vocab: Axis, config: Gpt2Config, *, key) -> 'BackpackGpt2Embeddings':
(k_wte, k_wp... |
class TestGridworld(unittest.TestCase):
def setUp(self):
self.base_mdp = OvercookedGridworld.from_layout_name('mdp_test', **{'cook_time': 5, 'start_order_list': ['onion', 'any']})
def test_constructor_invalid_inputs(self):
with self.assertRaises(AssertionError):
mdp = OvercookedGridw... |
def test_ufuncs_on_records_1439_without_warning():
def overload_abs(self):
return np.sqrt(((self.x ** 2) + (self.y ** 2)))
behavior = {}
behavior[(np.absolute, 'Overload')] = overload_abs
one = ak.Array([[{'x': 4, 'y': 3}, {'x': 6, 'y': 8}, {'x': 5, 'y': 12}], [], [{'x': 9, 'y': 12}, {'x': 15, '... |
def test_validator_combine_objectives_bad_obj_results():
v = Validator(model, dataloader, metrics, objectives)
with pytest.raises(TypeError, match='Argument: obj_results must be set.'):
v.combine_objectives(None, alphas, max_normalization)
with pytest.raises(TypeError, match=('Argument:' + ' obj_res... |
class WindowsLibtorchConfigNode(ConfigNode):
def __init__(self, parent, libtorch_config_variant):
super(WindowsLibtorchConfigNode, self).__init__(parent, ('LIBTORCH_CONFIG_VARIANT=' + str(libtorch_config_variant)))
self.props['libtorch_config_variant'] = libtorch_config_variant
def get_children(... |
def test_fields_in_90pct_credible_region(bench, random_fields, random_sky_map):
cum_prob = sa.func.sum((SkymapTile.probdensity * SkymapTile.hpx.area)).over(order_by=SkymapTile.probdensity.desc()).label('cum_prob')
subquery1 = sa.select(SkymapTile.probdensity, cum_prob).filter((SkymapTile.id == 1)).subquery()
... |
class SkewPolynomialRing_finite_field(SkewPolynomialRing_finite_order):
def __init__(self, base_ring, morphism, derivation, names, sparse, category=None):
if (self.Element is None):
import sage.rings.polynomial.skew_polynomial_finite_field
self.Element = sage.rings.polynomial.skew_po... |
def test_counting_with_frequentist_calculator():
(loss, Nsig) = create_loss_counting()
calculator = FrequentistCalculator(loss, Minuit(), ntoysnull=1000)
poinull = POI(Nsig, 0)
discovery_test = Discovery(calculator, poinull)
(pnull, significance) = discovery_test.result()
assert (significance < ... |
class Printer(Visitor, Text):
def __init__(self, factor_prefixes=False, c2_syntax=True):
super(Visitor, self).__init__()
super(Text, self).__init__()
self.factor_prefixes = factor_prefixes
self.c2_syntax = c2_syntax
self.c2_net_name = None |
class CondConvResidual(InvertedResidual):
def __init__(self, in_chs, out_chs, dw_kernel_size=3, stride=1, dilation=1, group_size=1, pad_type='', noskip=False, exp_ratio=1.0, exp_kernel_size=1, pw_kernel_size=1, act_layer=tf.keras.layers.ReLU, norm_layer=tf.keras.layers.BatchNormalization, se_layer=None, num_experts... |
def violin(df_dfc):
(fig, ax) = plt.subplots(1, 1, figsize=(15, 9))
dfc_mean = df_dfc.abs().mean()
N = 10
sorted_ix = dfc_mean.abs().sort_values()[(- N):].index
parts = ax.violinplot([df_dfc[w] for w in sorted_ix], vert=False, showextrema=False, showmeans=False, showmedians=False, widths=0.7, positi... |
def getObjsFromPrepositions(deps):
objs = []
for dep in deps:
if ((dep.pos_ == 'ADP') and (dep.dep_ == 'prep')):
objs.extend([tok for tok in dep.rights if (tok.dep_ in OBJECTS)])
return objs |
class SymforceCCSymTest(TestCase):
def test_key(self) -> None:
with self.subTest(msg='static member fields were wrapped'):
self.assertIsInstance(cc_sym.Key.INVALID_LETTER, str)
self.assertIsInstance(cc_sym.Key.INVALID_SUB, int)
self.assertIsInstance(cc_sym.Key.INVALID_SUP... |
class TFXLNetMainLayer(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
_with_task('Doing naive query')
def naive_query(features, deep_feats, color_feats, labels, retrieval_top_n=5):
results = get_deep_color_top_n(features, deep_feats, color_feats, labels, retrieval_top_n)
return results |
def graph_preparation_runner(in_model: Any, representative_data_gen: Callable, quantization_config: QuantizationConfig, fw_info: FrameworkInfo, fw_impl: FrameworkImplementation, tpc: TargetPlatformCapabilities, tb_w: TensorboardWriter=None, mixed_precision_enable: bool=False) -> Graph:
graph = read_model_to_graph(i... |
def train_epoch(model_gen, model_dis2, model_dis4, model_dis1=None, optim_gen=None, optim_dis2=None, optim_dis4=None, optim_dis1=None, trainA_iterator=None, trainB_iterator=None):
source_domain_label = 1
target_domain_label = 0
smooth = 1e-07
model_gen.train()
if args.d1:
model_dis1.train()
... |
class BartForSequenceClassification():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
class Partition13(nn.Module):
LAYER_SCOPES = ['T5ForConditionalGeneration/T5Stack[decoder]/T5Block[15]', 'T5ForConditionalGeneration/T5Stack[decoder]/T5Block[16]', 'T5ForConditionalGeneration/T5Stack[decoder]/T5Block[17]']
TENSORS = []
def __init__(self, layers, tensors, device='cuda:13'):
super()._... |
class ReplicationPad1d(_ReplicationPadNd):
padding: Tuple[(int, int)]
def __init__(self, padding: _size_2_t) -> None:
super(ReplicationPad1d, self).__init__()
self.padding = _pair(padding) |
def start_training():
logger.info('Setup config, data and model...')
opt = BaseOptions().parse()
set_seed(opt.seed)
config = {}
config = update_config(opt, config)
tb_writer = SummaryWriter(opt.tensorboard_log_dir)
qfvs_split = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2, 4], 4: [1, 2, 3]}
sco... |
def is_valid_outcome_range(dx, code_range):
for code in code_range:
if dx.startswith(code):
return True
return False |
def create_relation_type(type_dict, path):
print('Creating relation_type dictionary...')
dic = {}
for f in path:
dic_kb = json.load(open(f, 'r'))
for idx in tqdm(dic_kb, total=len(dic_kb)):
try:
idx_type = type_dict[get_id(idx)]
except:
... |
class FixedParam(RandomHyperparameter):
def __init__(self, name, value):
super().__init__(name)
self._value = value
def generate_next_value(self):
return self._value |
class TrainableSupportsPredictJoint(TrainableProbabilisticModel, SupportsPredictJoint, Protocol):
pass |
def bch_bound(n, D, arithmetic=False):
def longest_streak(step):
max_len = 1
max_offset = 0
j = 0
while (j < n):
h = j
while isD[((h * step) % n)]:
h += 1
if ((h - j) > max_len):
max_offset = ((j * step) % n)
... |
def prepare_inception_moments(dataloader, eval_mode, generator, inception_model, splits, run_name, logger, device):
dataset_name = dataloader.dataset.dataset_name
inception_model.eval()
save_path = os.path.abspath(os.path.join('./data', ((((dataset_name + '_') + eval_mode) + '_') + 'inception_moments.npz'))... |
def assert_and_infer_cfg(cache_urls=True):
if (__C.MODEL.RPN_ONLY or __C.MODEL.FASTER_RCNN):
__C.RPN.RPN_ON = True
if (__C.RPN.RPN_ON or __C.RETINANET.RETINANET_ON):
__C.TEST.PRECOMPUTED_PROPOSALS = False
if cache_urls:
cache_cfg_urls() |
def layer_norm(input, normalized_shape, weight=None, bias=None, eps=1e-05):
return torch.layer_norm(input, normalized_shape, weight, bias, eps, torch.backends.cudnn.enabled) |
class WarmRestartPlateau(torch.optim.lr_scheduler.ReduceLROnPlateau):
def __init__(self, T_restart, *args, **kwargs):
super().__init__(*args, **kwargs)
self.T_restart = T_restart
self.base_lrs = [group['lr'] for group in self.optimizer.param_groups]
def step(self, *args, **kwargs):
... |
class NodeAttrEq(LogicalValue):
def __init__(self, attr: str, value):
self.attr = attr
self.value = value
def evaluate(self, node: GraphNode, **kwargs):
return (self.value == getattr(node, self.attr)) |
class UnlabeledDataset(Dataset):
def __init__(self, csv_path):
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
impressions = bert_tokenizer.get_impressions_from_csv(csv_path)
self.encoded_imp = bert_tokenizer.tokenize(impressions, tokenizer)
def __len__(self):
retu... |
class CBSubSwinTransformer(SwinTransformerOriginal):
def _freeze_stages(self):
if ((self.frozen_stages >= 0) and hasattr(self, 'patch_embed')):
self.patch_embed.eval()
for param in self.patch_embed.parameters():
param.requires_grad = False
if ((self.frozen_sta... |
_vision
class FlavaProcessorTest(unittest.TestCase):
def setUp(self):
self.tmpdirname = tempfile.mkdtemp()
vocab_tokens = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest']
self.vocab_file = os.path.join(self.tmpdirname... |
def get_lexicon():
global lexicon
if (not lexicon):
lexicon = make_lexicon()
return lexicon |
def generate_many_k_regular_graphs(k, n, N, seed=0):
ngraph = int(ceil((N / n)))
graphs = [generate_k_regular(k, n, s) for s in range(seed, (seed + ngraph))]
index_base = 0
edge_list = []
for graph in graphs:
edge_list.extend([((src + index_base), (dst + index_base)) for (src, dst) in list(g... |
def remote_copy(remote_machine, local_path, remote_path, port=22):
cmd = ('ssh -p %d %s "mkdir -p %s"' % (port, remote_machine, remote_path))
parallax_log.warning(colored(('\n$ %s' % cmd), 'red'))
os.system(cmd)
cmd = ('scp -P %d %s %s:%s' % (port, local_path, remote_machine, remote_path))
parallax_... |
def main():
for i in list(range(4))[::(- 1)]:
print((i + 1))
time.sleep(1)
paused = False
while True:
if (not paused):
screen = np.array(ImageGrab.grab(bbox=(0, 40, 960, 560)))
timing = datetime.datetime.now()
training_data.append([screen, timing])... |
class PlyData(object):
def __init__(self, elements=[], text=False, byte_order='=', comments=[], obj_info=[]):
if ((byte_order == '=') and (not text)):
byte_order = _native_byte_order
self.byte_order = byte_order
self.text = text
self.comments = list(comments)
self... |
def _to_op(tensor_or_op):
if hasattr(tensor_or_op, 'op'):
return tensor_or_op.op
return tensor_or_op |
_to_string_io
def load_annotation(fhandle: TextIO) -> annotations.MultiAnnotator:
df = pd.read_csv(fhandle)
annotators = []
annotations_ = []
for (id, dfa) in df.groupby('annotator'):
intervals = dfa[['onset', 'offset']].values
label = dfa['event_label'].tolist()
events = annotat... |
def register_functions(root_module):
module = root_module
register_functions_ns3_FatalImpl(module.add_cpp_namespace('FatalImpl'), root_module)
register_functions_ns3_Hash(module.add_cpp_namespace('Hash'), root_module)
register_functions_ns3_TracedValueCallback(module.add_cpp_namespace('TracedValueCallba... |
class SearchJob(GenericJob):
def __init__(self, problem):
self.type = 'searchfragment'
GenericJob.__init__(self, problem)
self.model = None
self.fragments = None
def run(self):
print(('Process [%s]: %s running %s with model %d' % (os.getpid(), self.type, self.problem_name... |
_grad()
def convert_chinese_clip_checkpoint(checkpoint_path, pytorch_dump_folder_path, config_path=None):
assert (config_path is not None), 'Please specify the ChineseCLIP model config of the corresponding model size.'
config = ChineseCLIPConfig.from_pretrained(config_path)
hf_model = ChineseCLIPModel(confi... |
class IndexedFreeAbelianMonoidElement(IndexedMonoidElement):
def __init__(self, F, x):
IndexedMonoidElement.__init__(self, F, dict(x))
def _sorted_items(self):
print_options = self.parent().print_options()
v = list(self._monomial.items())
try:
v.sort(key=print_options... |
def load_params_LLM(config, model, fold_data):
no_decay = ['bias', 'LayerNorm.weight']
named = list(model.named_parameters())
no_decay = ['bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [{'params': [p for (n, p) in named if (not any(((nd in n) for nd in no_decay)))], 'lr': float(config.bert_l... |
def p2_2partitions_all_models():
for model in ['wrn_16x4_c100_p2', 'wrn_28x10_c100_dr03_p2']:
plt.figure()
p2_2partitions(model) |
class TestGIL(object):
def setup_method(self):
self.messages = []
def log(self, message):
self.messages.append(message)
def make_worker_thread(self, target, args):
log = self.log
class WorkerThread(threading.Thread):
def run(self):
log('interpolati... |
class ParentFinder():
_parent_map: Dict[(Node, Node)]
def __init__(self, prog: Node):
self._parent_map = dict()
for node in dfs(prog):
for child in node.children:
self._parent_map[child] = node
def get_parent(self, node: Node) -> Optional[Node]:
return sel... |
class Graph(object):
def __init__(self):
self._nodes = {}
def add_edge(self, s, t, label):
s_targets = self._nodes.setdefault(s, {})
s_targets.setdefault(t, set()).add(label)
def nodes(self):
return self._nodes
def __iter__(self):
return iter(self._nodes) |
class AbsCnxp(FunCnxp):
sig = (Constant,)
code = 'abs'
def type_constraints(self, tcs):
tcs.number(self)
tcs.eq_types(self, self._args[0]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.