code stringlengths 281 23.7M |
|---|
class DenseUnit(nn.Module):
def __init__(self, in_channels, out_channels, dropout_rate):
super(DenseUnit, self).__init__()
self.use_dropout = (dropout_rate != 0.0)
bn_size = 4
inc_channels = (out_channels - in_channels)
mid_channels = (inc_channels * bn_size)
self.con... |
def test_inference_without_dataset_info():
pose_model = init_pose_model('configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/res50_coco_256x192.py', None, device='cpu')
if ('dataset_info' in pose_model.cfg):
_ = pose_model.cfg.pop('dataset_info')
image_name = 'tests/data/coco/.jpg'
person_res... |
class Controls(dict):
_buttons = ('mouse1', 'mouse2', 'mouse3', 'mouse4', 'mouse5', 'wheel')
_buttons += ('arrowleft', 'arrowright', 'arrowup', 'arrowdown')
_buttons += ('tab', 'enter', 'escape', 'backspace', 'delete')
_buttons += ('shift', 'control')
_modes = ('drag', 'push', 'peek', 'repeat')
... |
class Fnode(nn.Module):
def __init__(self, combine: nn.Module, after_combine: nn.Module):
super(Fnode, self).__init__()
self.combine = combine
self.after_combine = after_combine
def forward(self, x: List[torch.Tensor]) -> torch.Tensor:
return self.after_combine(self.combine(x)) |
def Parser():
parser = argparse.ArgumentParser()
parser.add_argument('--root', type=str, default='../data/example_data', help='rio path')
parser.add_argument('--type', type=str, default='train', choices=['train', 'test', 'validation'], help='allow multiple rel pred outputs per pair', required=False)
par... |
def test_tb05ad_resonance():
A = np.array([[0, (- 1)], [1, 0]])
B = np.array([[1], [0]])
C = np.array([[0, 1]])
jomega = 1j
with pytest.raises(SlycotArithmeticError, match='Either `freq`.* is too near to an eigenvalue of A,\\nor `rcond` is less than the machine precision EPS.') as cm:
transf... |
def make_talabel_seg_list(utt_index_list, utt_list, utt_len_list, seg_len, utt2talabels):
seg_list = []
for utt_index in utt_index_list:
utt_id = utt_list[utt_index]
utt_len = utt_len_list[utt_index]
utt_segs = [talabel.get_centered_seg(seg_len, max_t=utt_len) for talabel in utt2talabels... |
class FSThread(threading.Thread):
def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None):
super().__init__(group=group, target=target, name=name, args=args, kwargs=kwargs, daemon=daemon)
self.err = None
def check_and_raise_error(self):
if (not self.e... |
def test_fix_ansi_codes_for_github_actions():
input = textwrap.dedent('\n This line is normal\n \x1b[1mThis line is bold\n This line is also bold\n \x1b[31m this line is red and bold\n This line is red and bold, too\x1b[0m\n This line is normal again\n ')
expecte... |
def test_assertrepr_loaded_per_dir(pytester: Pytester) -> None:
pytester.makepyfile(test_base=['def test_base(): assert 1 == 2'])
a = pytester.mkdir('a')
a.joinpath('test_a.py').write_text('def test_a(): assert 1 == 2', encoding='utf-8')
a.joinpath('conftest.py').write_text('def pytest_assertrepr_compar... |
def make_os_version_info(archbits: int, *, wide: bool):
Struct = struct.get_aligned_struct(archbits)
char_type = (ctypes.c_wchar if wide else ctypes.c_char)
class OSVERSIONINFO(Struct):
_fields_ = (('dwOSVersionInfoSize', ctypes.c_uint32), ('dwMajorVersion', ctypes.c_uint32), ('dwMinorVersion', ctyp... |
def plot_err_with_without_post_process(fig=None, ax_arr=None, big_ax=None, dpi=300, figsize=(2.83, 5.5)):
if ((fig is None) and (ax_arr is None)):
(fig, ax_arr) = plt.subplots(2, 1, dpi=dpi, figsize=figsize)
metrics = ['avg_error', 'avg_segment_error_rate']
for ax_ in ax_arr.flatten():
ax_.t... |
def get_video_trans():
train_trans = video_transforms.Compose([video_transforms.RandomHorizontalFlip(), video_transforms.Resize((200, 112)), video_transforms.RandomCrop(112), volume_transforms.ClipToTensor(), video_transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])
test_trans = video_... |
def test_local_variables_should_be_displayed_when_showlocals_option_is_used(pytester):
pytester.makefile('.feature', test=FEATURE)
pytester.makepyfile(textwrap.dedent(' from pytest_bdd import given, when, then, scenario\n\n\n (\'there is a bar\')\n def _():\n return \'bar\'\n\n ... |
class TesttestMatIO():
def setup_method(self):
self.test_file = test_file = pysal_examples.get_path('spat-sym-us.mat')
self.obj = MatIO(test_file, 'r')
def test_close(self):
f = self.obj
f.close()
pytest.raises(ValueError, f.read)
def test_read(self):
w = self... |
class GenericBase(CommonBaseTesting):
fake_ctrl = CommonBase.control('C{ch}:control?', 'C{ch}:control %d', 'docs', validator=truncated_range, values=(1, 10), dynamic=True)
fake_setting = CommonBase.setting('C{ch}:setting %d', 'docs', validator=truncated_range, values=(1, 10), dynamic=True)
fake_measurement ... |
class _MSDataLoaderIter(_DataLoaderIter):
def __init__(self, loader):
self.dataset = loader.dataset
self.scale = loader.scale
self.collate_fn = loader.collate_fn
self.batch_sampler = loader.batch_sampler
self.num_workers = loader.num_workers
self.pin_memory = (loader.... |
def test_linop_no_init_err():
mat = torch.rand((3, 1, 2))
x = torch.rand(2)
linop = LinOpWithoutInit(mat)
try:
y = linop.mv(x)
msg = 'A RuntimeError must be raised when a LinearOperator is called without .__init__() called first'
assert False, msg
except RuntimeError as e:
... |
class StateSelect(widgets.Select):
def render(self, name, value, attrs=None, *args, **kwargs):
if isinstance(value, base.StateWrapper):
state_name = value.state.name
elif isinstance(value, base.State):
state_name = value.name
else:
state_name = str(value)
... |
def _get_reader_kwargs(reader, reader_kwargs):
reader_kwargs = (reader_kwargs or {})
if (reader is None):
reader_kwargs = {None: reader_kwargs}
elif (reader_kwargs.keys() != set(reader)):
reader_kwargs = dict.fromkeys(reader, reader_kwargs)
reader_kwargs_without_filter = {}
for (k, v... |
def test_interleave_with_mask():
a = np.arange(6)
b = np.arange(6, 12)
c = np.arange(12, 18)
assert (a.shape[0] == b.shape[0] == c.shape[0])
n = a.shape[0]
a_buf = np.empty((n * INT32_BUF_SIZE), dtype=np.uint8)
b_buf = np.empty((n * INT32_BUF_SIZE), dtype=np.uint8)
c_buf = np.empty((n * ... |
def stack_images_PIL(imgs, shape=None, individual_img_size=None):
assert (len(imgs) > 0), 'No images received.'
if (shape is None):
size = int(np.ceil(np.sqrt(len(imgs))))
shape = [int(np.ceil((len(imgs) / size))), size]
else:
if isinstance(shape, numbers.Number):
shape =... |
class _MultipleMatch(ParseElementEnhance):
def __init__(self, expr, stopOn=None):
super().__init__(expr)
self.saveAsList = True
ender = stopOn
if isinstance(ender, str_type):
ender = self._literalStringClass(ender)
self.stopOn(ender)
def stopOn(self, ender):
... |
class TransformerLanguageModelConfig(FairseqDataclass):
activation_fn: ChoiceEnum(utils.get_available_activation_fns()) = field(default='relu', metadata={'help': 'activation function to use'})
dropout: float = field(default=0.1, metadata={'help': 'dropout probability'})
attention_dropout: float = field(defa... |
def all_coarse_grains_for_blackbox(blackbox):
for partition in all_partitions(blackbox.output_indices):
for grouping in all_groupings(partition):
coarse_grain = CoarseGrain(partition, grouping)
try:
validate.blackbox_and_coarse_grain(blackbox, coarse_grain)
... |
def alexandrov(space: LengthSpace, pt_a: Point, pt_b: Point, pt_c: Point) -> Scalar:
pt_d = midpoint(space, pt_a, pt_c)
bisector_lenth = space.length(pt_b, pt_d)
euclidean_bisector_length = _bisector_length(space.length(pt_a, pt_b), space.length(pt_b, pt_c), space.length(pt_a, pt_c))
return (bisector_le... |
def convert(source_dir: Path, dest_dir):
dest_dir = Path(dest_dir)
dest_dir.mkdir(exist_ok=True)
opus_state = OpusState(source_dir)
opus_state.tokenizer.save_pretrained(dest_dir)
model = opus_state.load_marian_model()
model = model.half()
model.save_pretrained(dest_dir)
model.from_pretra... |
def parity_to_cmd(node: Dict, datadir: str, chain_id: int, chain_spec: str, verbosity: str) -> Command:
node_config = {'nodekeyhex': 'node-key', 'password': 'password', 'port': 'port', 'rpcport': 'jsonrpc-port', 'pruning-history': 'pruning-history', 'pruning': 'pruning', 'pruning-memory': 'pruning-memory', 'cache-s... |
def processor_to_arch():
if (Processor.type == ProcessorType.PLFM_386):
return (ArchX64 if (Processor.mode == ArchMode.MODE64) else ArchX86)
elif (Processor.type == ProcessorType.PLFM_ARM):
return (ArchARM64 if (Processor.mode == ArchMode.MODE64) else ArchARM)
else:
assert False |
class Migration(migrations.Migration):
dependencies = [('conditions', '0015_move_attribute_to_attributeentity'), ('projects', '0022_move_attribute_to_attributeentity'), ('tasks', '0012_move_attribute_to_attributeentity'), ('domain', '0036_remove_range_and_verbosename')]
operations = [migrations.AddField(model_n... |
def diff_iloc(dfs, new, window=None):
dfs = deque(dfs)
if (len(new) > 0):
dfs.append(new)
old = []
if (len(dfs) > 0):
n = (sum(map(len, dfs)) - window)
while (n > 0):
if (len(dfs[0]) <= n):
df = dfs.popleft()
old.append(df)
... |
class GraphDataBetween(GraphData_Base):
def draw(self, axis, figure=None):
(x, y1, y2) = self.data
axis.fill_between(x, y1, y2, **self.line_format)
if ('label' in self.line_format):
patch_color = {}
patch_color.update(self.line_format)
p = Rectangle((0, 0)... |
class ModelPool():
def __init__(self, dic_path, dic_exp_conf):
self.dic_path = dic_path
self.exp_conf = dic_exp_conf
self.num_best_model = self.exp_conf['NUM_BEST_MODEL']
if os.path.exists(os.path.join(self.dic_path['PATH_TO_WORK_DIRECTORY'], 'best_model.pkl')):
self.best... |
def sync_perform(dispatcher, effect):
successes = []
errors = []
effect = effect.on(success=successes.append, error=errors.append)
perform(dispatcher, effect)
if successes:
return successes[0]
elif errors:
raise errors[0]
else:
raise NotSynchronousError(('Performing %... |
class LatticeModelResult(EigenstateResult):
def __init__(self) -> None:
super().__init__()
self._algorithm_result: Optional[AlgorithmResult] = None
self._computed_lattice_energies: Optional[np.ndarray] = None
self._num_occupied_modals_per_mode: Optional[List[List[float]]] = None
... |
class TrainOptions(BaseOptions):
def initialize(self):
BaseOptions.initialize(self)
self._parser.add_argument('--print_freq_s', type=int, default=5, help='frequency of showing training results on console')
self._parser.add_argument('--lr_policy', type=str, default='step', choices=['lambda', ... |
def test_plugin_dependencies_unmet(hatch, config_file, helpers, temp_dir, mock_plugin_installation):
config_file.model.template.plugins['default']['tests'] = False
config_file.save()
project_name = 'My.App'
with temp_dir.as_cwd():
result = hatch('new', project_name)
assert (result.exit_code ... |
class Leaf(Base):
_prefix = ''
lineno = 0
column = 0
def __init__(self, type, value, context=None, prefix=None, fixers_applied=[]):
assert (0 <= type < 256), type
if (context is not None):
(self._prefix, (self.lineno, self.column)) = context
self.type = type
s... |
def looks_like_an_export(sexp):
if (not isinstance(sexp, values.W_Cons)):
return False
if (sexp.car() is not export_sym):
return False
if (not isinstance(sexp.cdr(), values.W_Cons)):
return False
if (not isinstance(sexp.cdr().cdr(), values.W_Cons)):
return False
if (n... |
class BCE_Loss(nn.Module):
def __init__(self):
super(BCE_Loss, self).__init__()
self.loss = nn.BCEWithLogitsLoss(reduction='none')
def forward(self, output, label):
(output, label) = (output.view((- 1), 1), label.view((- 1), 1))
loss = self.loss(output, label.view((- 1), 1))
... |
def train(args, train_env, val_envs, aug_env=None, rank=(- 1)):
default_gpu = is_default_gpu(args)
if default_gpu:
with open(os.path.join(args.log_dir, 'training_args.json'), 'w') as outf:
json.dump(vars(args), outf, indent=4)
writer = SummaryWriter(log_dir=args.log_dir)
reco... |
def _get_boolability_no_mvv(value: Value) -> Boolability:
if isinstance(value, AnnotatedValue):
value = value.value
value = replace_known_sequence_value(value)
if isinstance(value, AnyValue):
return Boolability.boolable
elif isinstance(value, UnboundMethodValue):
if value.seconda... |
_fixtures(WebFixture)
def test_reading_cookies_on_initialising_a_session(web_fixture):
fixture = web_fixture
UserSession.initialise_web_session_on(fixture.context)
assert (not fixture.context.session.is_active())
assert (not fixture.context.session.is_secured())
fixture.context.session = None
us... |
def save_as_tf_module_multi_gpu(loading_path: 'str', saving_path: 'str', compressed_ops: List['str'], input_shape: Tuple):
def trace_model(inputs):
tf.keras.backend.set_learning_phase(1)
model = load_tf_sess_variables_to_keras_single_gpu(loading_path, compressed_ops)
train_out = model(inputs... |
def convert(src, dst):
regnet_model = torch.load(src)
blobs = regnet_model['model_state']
state_dict = OrderedDict()
converted_names = set()
for (key, weight) in blobs.items():
if ('stem' in key):
convert_stem(key, weight, state_dict, converted_names)
elif ('head' in key)... |
def test_run_pyscript_py_locals(base_app, request):
test_dir = os.path.dirname(request.module.__file__)
python_script = os.path.join(test_dir, 'pyscript', 'py_locals.py')
base_app.py_locals['test_var'] = 5
base_app.py_locals['my_list'] = []
run_cmd(base_app, 'run_pyscript {}'.format(python_script))
... |
def test_plural_within_rules():
p = plural.PluralRule({'one': 'n is 1', 'few': 'n within 2,4,7..9'})
assert (repr(p) == "<PluralRule 'one: n is 1, few: n within 2,4,7..9'>")
assert (plural.to_javascript(p) == "(function(n) { return ((n == 2) || (n == 4) || (n >= 7 && n <= 9)) ? 'few' : (n == 1) ? 'one' : 'o... |
def _git_str() -> Optional[str]:
commit = None
if (not hasattr(sys, 'frozen')):
try:
gitpath = os.path.join(os.path.dirname(os.path.realpath(__file__)), os.path.pardir, os.path.pardir)
except (NameError, OSError):
log.misc.exception('Error while getting git path')
... |
def _get_jk_kshift(mf, dm_kpts, hermi, kpts, kshift, with_j=True, with_k=True):
from pyscf.pbc.df.df_jk import get_j_kpts_kshift, get_k_kpts_kshift
vj = vk = None
if with_j:
vj = get_j_kpts_kshift(mf.with_df, dm_kpts, kshift, hermi=hermi, kpts=kpts)
if with_k:
vk = get_k_kpts_kshift(mf.w... |
def test_PVSystem_get_ac_pvwatts_multi(pvwatts_system_defaults, pvwatts_system_kwargs, mocker):
mocker.spy(inverter, 'pvwatts_multi')
expected = [pd.Series([0.0, 48.123524, 86.4]), pd.Series([0.0, 45.89355, 85.5])]
systems = [pvwatts_system_defaults, pvwatts_system_kwargs]
for (base_sys, exp) in zip(sys... |
class Encoder(nn.Module):
def __init__(self, in_channels, num_classes):
super().__init__()
self.initial_block = DownsamplerBlock(in_channels, 16)
self.layers = nn.ModuleList()
self.layers.append(DownsamplerBlock(16, 64))
for x in range(0, 5):
self.layers.append(no... |
def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')):
(model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
(model_args, dat... |
class PyTorchDiscriminator(DiscriminativeNetwork):
def __init__(self, n_features: int=1, n_out: int=1) -> None:
super().__init__()
if (not _HAS_TORCH):
raise MissingOptionalLibraryError(libname='Pytorch', name='PyTorchDiscriminator', pip_install="pip install 'qiskit-aqua[torch]'")
... |
class DOCIHamiltonianTest(unittest.TestCase):
def setUp(self):
self.geometry = [('H', (0.0, 0.0, 0.0)), ('H', (0.0, 0.0, 0.7414))]
self.basis = 'sto-3g'
self.multiplicity = 1
self.filename = os.path.join(DATA_DIRECTORY, 'H2_sto-3g_singlet_0.7414')
self.molecule = MolecularDat... |
def test_1epoch(class_limit=None, n_snip=5, opt_flow_len=10, image_shape=(224, 224), original_image_shape=(341, 256), batch_size=16, saved_weights=None):
print(('\nValidating for weights: %s\n' % saved_weights))
data = DataSet(class_limit, image_shape, original_image_shape, n_snip, opt_flow_len, batch_size)
... |
def forward(apps: Apps, schema_editor: BaseDatabaseSchemaEditor) -> None:
filter_: pydis_site.apps.api.models.Filter = apps.get_model('api', 'Filter')
filter_list: pydis_site.apps.api.models.FilterList = apps.get_model('api', 'FilterList')
filter_list_old = apps.get_model('api', 'FilterListOld')
for (na... |
class Trainer(object):
def __init__(self, device, dicts, opt, constants=None, setup_optimizer=True):
self.device = device
opt.node_rank = 0
opt.nodes = 1
self.world_size = len(opt.gpus)
self.constants = (dill.loads(constants) if (constants is not None) else None)
self... |
class TestSetScreenSaver(EndianTest):
def setUp(self):
self.req_args_0 = {'allow_exposures': 2, 'interval': (- 25214), 'prefer_blank': 0, 'timeout': (- 24531)}
self.req_bin_0 = b'k\x00\x00\x03\xa0-\x9d\x82\x00\x02\x00\x00'
def testPackRequest0(self):
bin = request.SetScreenSaver._request... |
class AttrVI_ATTR_USB_INTFC_NUM(RangeAttribute):
resources = [(constants.InterfaceType.usb, 'INSTR'), (constants.InterfaceType.usb, 'RAW')]
py_name = 'interface_number'
visa_name = 'VI_ATTR_USB_INTFC_NUM'
visa_type = 'ViInt16'
default = 0
(read, write, local) = (True, False, False)
(min_valu... |
def show_account_sub(call, email):
t = f''' <code>{email}</code>
'''
bot.edit_message_text(text=(t + '...'), chat_id=call.from_user.id, message_id=call.message.message_id, parse_mode='HTML')
refresh_token = RefreshToken().get(email)
az_sub = Subscription(refresh_token)
subs = az_sub.list()
for s... |
def test_spectral_factor_firstsolar_range():
with pytest.warns(UserWarning, match='Exceptionally high pw values'):
out = spectrum.spectral_factor_firstsolar(np.array([0.1, 3, 10]), np.array([1, 3, 5]), module_type='monosi')
expected = np.array([0., 1., np.nan])
assert_allclose(out, expected, atol=0.... |
def make_result_folders(output_directory):
image_directory = os.path.join(output_directory, 'images')
if (not os.path.exists(image_directory)):
print('Creating directory: {}'.format(image_directory))
os.makedirs(image_directory)
checkpoint_directory = os.path.join(output_directory, 'checkpoi... |
.skipif((not torch.cuda.is_available()), reason='requires CUDA support')
.parametrize('channels', [4, 30, 32, 64, 71, 1025])
def test_gradient_numerical(channels, grad_value=True, grad_sampling_loc=True, grad_attn_weight=True):
(N, M, _) = (1, 2, 2)
(Lq, L, P) = (2, 2, 2)
shapes = torch.as_tensor([(3, 2), (... |
class Plugin():
PLUGIN_ID: ClassVar[str] = xbmcaddon.Addon().getAddonInfo('id')
PLUGIN_URL: ClassVar[str] = f'plugin://{PLUGIN_ID}'
settings: ClassVar[Settings] = Settings()
def __init__(self) -> None:
self.path = (urlsplit(sys.argv[0]).path or '/')
self.handle = int(sys.argv[1])
... |
def test_nested_process_search_unsupported_field(s1_product: SentinelOne):
criteria = {'foo': 'bar'}
s1_product._queries = {}
s1_product._pq = False
s1_product.log = logging.getLogger('pytest_surveyor')
s1_product.nested_process_search(Tag('unsupported_field'), criteria, {})
assert (len(s1_produ... |
def cov_xPrime_maxGrad(xPrime, value_at_max, sigma, l):
d = len(value_at_max)
num_of_xPrime = len(xPrime)
cov_matrix = np.zeros((num_of_xPrime, d))
for i in range(num_of_xPrime):
for j in range(d):
cov_matrix[(i, j)] = cov_x_devY(xPrime[i], value_at_max, sigma, l, j)
return cov_m... |
class Finder():
def __init__(self, path: (Sequence[str] | None)=None) -> None:
self._path = (path or sys.path)
def find_module(self, modname: str, module_parts: Sequence[str], processed: list[str], submodule_path: (Sequence[str] | None)) -> (ModuleSpec | None):
def contribute_to_path(self, spec: Mod... |
_module()
class ImageToTensor(object):
def __init__(self, keys):
self.keys = keys
def __call__(self, results):
for key in self.keys:
img = results[key]
if (len(img.shape) < 3):
img = np.expand_dims(img, (- 1))
results[key] = to_tensor(img.trans... |
('/api/file_system/create_folder', methods=['POST'])
def create_folders() -> Response:
request_json = request.get_json()
(user_id, chat_id) = get_user_and_chat_id_from_request_json(request_json)
root_path = create_personal_folder(user_id)
if (os.path.exists(root_path) and os.path.isdir(root_path)):
... |
def dropNested(text, openDelim, closeDelim):
openRE = re.compile(openDelim, re.IGNORECASE)
closeRE = re.compile(closeDelim, re.IGNORECASE)
spans = []
nest = 0
start = openRE.search(text, 0)
if (not start):
return text
end = closeRE.search(text, start.end())
next = start
while... |
class TapBpm(SongsMenuPlugin):
PLUGIN_ID = 'Tap BPM'
PLUGIN_NAME = _('Tap BPM')
PLUGIN_DESC = _(' Tap BPM for the selected song.')
PLUGIN_ICON = Icons.EDIT
PLUGIN_VERSION = '0.1'
def plugin_song(self, song):
self._window = window = Dialog(title=_('Tap BPM'), parent=self.plugin_window)
... |
class GreasemonkeyScript():
def __init__(self, properties, code, filename=None):
self._code = code
self.includes: Sequence[str] = []
self.matches: Sequence[str] = []
self.excludes: Sequence[str] = []
self.requires: Sequence[str] = []
self.description = None
se... |
def test_h11_as_server() -> None:
with socket_server(H11RequestHandler) as
(host, port) =
url = f'
with closing(urlopen(url)) as f:
assert (f.getcode() == 200)
data = f.read()
info = json.loads(data.decode('ascii'))
print(info)
assert (info['method'] == ... |
class BuildCanceller(object):
def __init__(self, app=None):
self.build_manager_config = app.config.get('BUILD_MANAGER')
if ((app is None) or (self.build_manager_config is None)):
self.handler = NoopCanceller()
else:
self.handler = None
def try_cancel_build(self, u... |
def test_basic():
with pm.Model(coords={'test_dim': range(3)}) as m_old:
x = pm.Normal('x')
y = pm.Deterministic('y', (x + 1))
w = pm.HalfNormal('w', pm.math.exp(y))
z = pm.Normal('z', y, w, observed=[0, 1, 2], dims=('test_dim',))
pot = pm.Potential('pot', (x * 2))
(m_fgr... |
def upload_to_server(errors: List[NamedTuple], paths: List[str], config: Dict[(str, str)], url: str, version: str) -> None:
unique_id = get_hashed_id()
files = []
for path in paths:
f = open(path)
files.append(f)
upload = {str(i): f for (i, f) in enumerate(files)}
errors_dict = error... |
def get_model_and_config(model_args: argparse.Namespace):
labels = UD_HEAD_LABELS
label_map: Dict[(int, str)] = {i: label for (i, label) in enumerate(labels)}
num_labels = len(labels)
config_kwargs = {'cache_dir': model_args.cache_dir, 'revision': model_args.model_revision, 'use_auth_token': (model_args... |
def Todo():
(items, set_items) = reactpy.hooks.use_state([])
async def add_new_task(event):
if (event['key'] == 'Enter'):
set_items([*items, event['target']['value']])
tasks = []
for (index, text) in enumerate(items):
async def remove_task(event, index=index):
set... |
class FC3_Firstboot(KickstartCommand):
removedKeywords = KickstartCommand.removedKeywords
removedAttrs = KickstartCommand.removedAttrs
def __init__(self, writePriority=0, *args, **kwargs):
KickstartCommand.__init__(self, writePriority, *args, **kwargs)
self.op = self._getParser()
sel... |
def test_create_args(tmp_path, capfd):
if (utils.platform != 'linux'):
pytest.skip('the test is only relevant to the linux build')
project_dir = (tmp_path / 'project')
basic_project.generate(project_dir)
actual_wheels = utils.cibuildwheel_run(project_dir, add_env={'CIBW_BUILD': 'cp310-manylinux_... |
class CategoricalConvPolicy(StochasticPolicy, LayersPowered, Serializable):
def __init__(self, name, env_spec, conv_filters, conv_filter_sizes, conv_strides, conv_pads, hidden_sizes=[], hidden_nonlinearity=tf.nn.relu, output_nonlinearity=tf.nn.softmax, prob_network=None):
Serializable.quick_init(self, local... |
def initialize_filterbank(sample_rate, n_harmonic, semitone_scale):
low_midi = note_to_midi('C1')
high_note = hz_to_note((sample_rate / (2 * n_harmonic)))
high_midi = note_to_midi(high_note)
level = ((high_midi - low_midi) * semitone_scale)
midi = np.linspace(low_midi, high_midi, (level + 1))
hz... |
class PostgresExplainLexer(RegexLexer):
name = 'PostgreSQL EXPLAIN dialect'
aliases = ['postgres-explain']
filenames = ['*.explain']
mimetypes = ['text/x-postgresql-explain']
url = '
version_added = '2.15'
tokens = {'root': [('(:|\\(|\\)|ms|kB|->|\\.\\.|\\,)', Punctuation), ('(\\s+)', Whites... |
def train_translation_model(data_dir, arch, extra_flags=None, task='translation', run_validation=False):
train_parser = options.get_training_parser()
train_args = options.parse_args_and_arch(train_parser, (['--task', task, data_dir, '--save-dir', data_dir, '--arch', arch, '--lr', '0.05', '--max-tokens', '500', ... |
class MultiHeadedDotAttention(nn.Module):
def __init__(self, h, d_model, dropout=0.1, scale=1, project_k_v=1, use_output_layer=1, do_aoa=0, norm_q=0, dropout_aoa=0.3):
super(MultiHeadedDotAttention, self).__init__()
assert (((d_model * scale) % h) == 0)
self.d_k = ((d_model * scale) // h)
... |
def test_get_executable(tmpfolder):
assert (shell.get_executable('python') is not None)
assert (shell.get_executable('python', tmpfolder, include_path=False) is None)
python = Path(sys.executable).resolve()
bin_path = shell.get_executable('python', include_path=False, prefix=sys.prefix)
bin_path = P... |
def test_trajectory_reader(tmpdir):
tmpcatalog = os.path.join(tmpdir, 'my_catalog.xosc')
cf = xosc.CatalogFile()
cf.create_catalog(tmpcatalog, 'TrajectoryCatalog', 'My first miscobject catalog', 'Mandolin')
orig = xosc.Trajectory('my_trajectory', False)
orig.add_shape(xosc.Clothoid(0.1, 0.01, 100, x... |
class SingularityLexer(RegexLexer):
name = 'Singularity'
url = '
aliases = ['singularity']
filenames = ['*.def', 'Singularity']
version_added = '2.6'
flags = ((re.IGNORECASE | re.MULTILINE) | re.DOTALL)
_headers = '^(\\s*)(bootstrap|from|osversion|mirrorurl|include|registry|namespace|include... |
def print_all_threads():
global _state
assert _state, "Global variable '_state' not set"
for thread_state in _state.values():
print_thread_profile(thread_state)
print()
print('total - time spent to execute the function')
print('inline - time spent in the function itself')
print('slee... |
def perm_test_across_days(animal_day_transmats, animal_id, from_state, transition, n_perm=1000, alpha=0.05):
day_transmats_map = animal_day_transmats[animal_id]
days = list(day_transmats_map.keys())
pairs = permutations(days, 2)
condition_counter_map = {pair: (day_transmats_map[pair[0]].counts, day_tran... |
def get_images_tc(paths, labels, nb_samples=None, shuffle=True, is_val=False):
if (nb_samples is not None):
sampler = (lambda x: random.sample(x, nb_samples))
else:
sampler = (lambda x: x)
if (is_val is False):
images = [(i, os.path.join(path, image)) for (i, path) in zip(labels, pat... |
class DeltaFile(LikeFile):
def __init__(self, signature, new_file):
LikeFile.__init__(self, new_file)
if (type(signature) is bytes):
sig_string = signature
else:
self._check_file(signature)
sig_string = signature.read()
signature.close()
... |
class Bunch(Mapping):
def __init__(self, name, data):
self._name = str(name)
self._data = data
def __getitem__(self, k):
return self._data[k]
def __getattr__(self, a):
try:
return self._data[a]
except KeyError:
raise AttributeError(a)
def _... |
.parametrize('entry_point_values_by_group', [{ApplicationPlugin.group: ['FirstApplicationPlugin', 'SecondApplicationPlugin'], Plugin.group: ['FirstPlugin', 'SecondPlugin']}])
def test_show_displays_installed_plugins_with_multiple_plugins(app: PoetryTestApplication, tester: CommandTester) -> None:
tester.execute('')... |
class TOperonClear(TOperonBase):
def test_misc(self):
self.check_false(['clear'], False, True)
self.check_false(['clear', self.f], False, True)
self.check_true(['clear', '-a', self.f], False, False)
self.check_false(['-v', 'clear', '-e', self.f], False, True)
self.check_true(... |
class PointnetSAModuleMSG(_PointnetSAModuleBase):
def __init__(self, *, npoint: int, radii: List[float], nsamples: List[int], mlps: List[List[int]], bn: bool=True, use_xyz: bool=True, pool_method='max_pool'):
super().__init__()
assert (len(radii) == len(nsamples) == len(mlps))
self.npoint = ... |
def generate_diverse_samples(cfg):
sample_directory = create_sample_directory(cfg)
path = get_model_path(cfg.image_name, cfg.run_name)
model = Diffusion.load_from_checkpoint(path, model=NextNet(depth=cfg.network_depth), timesteps=cfg.diffusion_timesteps, training_target='x0', noise_schedule='linear').cuda()... |
def get_args():
parser = argparse.ArgumentParser(description='process the textgrid files')
parser.add_argument('--path', type=str, required=True, help='Data path')
parser.add_argument('--max_length', default=100000, type=float, help='overlap speech max time,if longger than max length should cut')
parser... |
def test_update_sections(db, settings):
xml_file = (((Path(settings.BASE_DIR) / 'xml') / 'elements') / 'sections.xml')
root = read_xml_file(xml_file)
version = root.attrib.get('version')
elements = flat_xml_to_elements(root)
elements = convert_elements(elements, version)
elements = order_element... |
class DreamBoothDataset(Dataset):
def __init__(self, concepts_list, tokenizer, with_prior_preservation=True, size=512, center_crop=False, num_class_images=None, pad_tokens=False, hflip=False):
self.size = size
self.center_crop = center_crop
self.tokenizer = tokenizer
self.with_prior_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.