code stringlengths 281 23.7M |
|---|
class Emojis(commands.Cog):
def __init__(self, bot: Bot) -> None:
self.bot = bot
def embed_builder(emoji: dict) -> tuple[(Embed, list[str])]:
embed = Embed(color=Colours.orange, title='Emoji Count', timestamp=datetime.now(tz=UTC))
msg = []
if (len(emoji) == 1):
for (c... |
def test_user_can_vote_if_has_ticket_for_a_previous_conference(user, conference, mocker, included_event_factory):
def side_effect(email, event_organizer, event_slug, additional_events):
return ((additional_events[0]['organizer_slug'] == 'organizer-slug') and (additional_events[0]['event_slug'] == 'event-slu... |
def test_extensions_only(hatch, temp_dir, helpers, config_file):
config_file.model.template.plugins['default']['src-layout'] = False
config_file.save()
project_name = 'My.App'
with temp_dir.as_cwd():
result = hatch('new', project_name)
assert (result.exit_code == 0), result.output
pa... |
class Observable():
def __init__(self):
self.observers: List[Observer] = []
def setChanged(self):
pass
def notifyObservers(self, value):
for observer in self.observers:
observer.update(self, value)
def addObserver(self, observer: Observer):
self.observers.appe... |
class Vector2():
__slots__ = ['x', 'y']
__hash__ = None
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __copy__(self):
return self.__class__(self.x, self.y)
copy = __copy__
def __repr__(self):
return ('Vector2(%.2f, %.2f)' % (self.x, self.y))
def __eq... |
def _process_attr_input_field(field: InputField, param_name_to_base_field: Dict[(str, BaseField)], has_custom_init: bool):
try:
base_field = param_name_to_base_field[field.id]
except KeyError:
return field
if ((not has_custom_init) and (field.type == Any) and (base_field.type == NoneType)):
... |
.skipif((not RAY_DATASET_AVAILABLE), reason='Ray datasets are not available in this version of Ray')
def test_simple_ray_dataset(start_client_server_5_cpus):
assert ray.util.client.ray.is_connected()
from xgboost_ray.examples.simple_ray_dataset import main
main(cpus_per_actor=1, num_actors=4) |
def test_debug_not_used(django_pytester: DjangoPytester) -> None:
django_pytester.create_test_module('\n from django.test import TestCase\n\n pre_setup_count = 0\n\n\n class TestClass1(TestCase):\n\n def debug(self):\n assert 0, "should not be called"\n\n de... |
def test_mspn_backbone():
with pytest.raises(AssertionError):
MSPN(num_stages=0)
with pytest.raises(AssertionError):
MSPN(num_units=1)
with pytest.raises(AssertionError):
MSPN(num_units=2, num_blocks=[2, 2, 2])
model = MSPN(num_stages=2, num_units=2, num_blocks=[2, 2])
model.... |
.parametrize('spoiler', [False, True])
.parametrize('layout', [{}, {'sky_temple_keys': LayoutSkyTempleKeyMode.ALL_GUARDIANS}, {'menu_mod': True, 'warp_to_start': False}])
def test_round_trip(spoiler: bool, layout: dict, default_echoes_preset, mocker):
random_uuid = uuid.uuid4()
mocker.patch('uuid.uuid4', return... |
class EntryCreate(LoginRequiredMixin, EntryCreateMixin, FormView):
template_name = 'dictionary/edit/entry_create.html'
def dispatch(self, request, *args, **kwargs):
self.extra_context = {'title': self.request.POST.get('title', '')}
return super().dispatch(request, *args, **kwargs)
def get_co... |
def test_get_macro_completion_items(base_app):
run_cmd(base_app, 'macro create foo !echo foo')
run_cmd(base_app, 'macro create bar !echo bar')
results = base_app._get_macro_completion_items()
assert (len(results) == len(base_app.macros))
for cur_res in results:
assert (cur_res in base_app.ma... |
class MultiResidual(nn.Module):
def __init__(self, scale, res_block, num_blocks):
super(MultiResidual, self).__init__()
assert (num_blocks >= 1)
self.scale = scale
self.res_blocks = nn.ModuleList([res_block() for _ in range(num_blocks)])
self.activ = nn.ReLU(inplace=False)
... |
def test_method_dynamic_instance_attr_2() -> None:
node = builder.extract_node('\n class A:\n # Note: no initializer, so the only assignment happens in get_x\n\n def get_x(self, x):\n self.x = x\n return self.x\n\n A().get_x(1) #\n ')
assert isinstance(node, nodes.N... |
def read_wid1(f):
line = f.readline()
if (not line.strip()):
raise EOF()
(wid1, stmin, imilli, nsamples, sta, channel_id, channel_name, sample_rate, system_type, data_format, diff_flag) = util.unpack_fixed('a4,x1,a17,x1,i3,x1,i8,x1,a6,x1,a8,x1,a2,x1,f11,x1,a6,x1,a4,x1,i1', line[:80])
if (wid1 !=... |
class PyAnalogClockPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(PyAnalogClockPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, core):
if self.initialized:
return
self.initialized = True
def isInitialized(... |
def _make_decorator(module: nn.Module, fun_name: str) -> Callable:
fun = getattr(module, fun_name)
from tensordict.nn.common import TensorDictModuleBase
(fun)
def new_fun(self, *args, **kwargs):
_is_stateless = self.__dict__.get('_is_stateless', False)
params = kwargs.pop('params', None)... |
class ConfigMultiRPaned(MultiRPaned):
def __init__(self, section, option):
super().__init__()
self.section = section
self.option = option
def set_widgets(self, widgets):
super().set_widgets(widgets)
paneds = self._get_paneds()
for paned in paneds:
pane... |
def generate_sparse_data(shape, num_points, num_channels, integer=False, data_range=((- 1), 1), with_dense=True, dtype=np.float32):
dense_shape = shape
ndim = len(dense_shape)
num_points = np.array(num_points)
batch_size = len(num_points)
batch_indices = []
coors_total = np.stack(np.meshgrid(*[n... |
('(int64, int64, float32[:], float32[:], float32[:], int32)', fastmath=False)
def rotate_iou_kernel_eval(N, K, dev_boxes, dev_query_boxes, dev_iou, criterion=(- 1)):
threadsPerBlock = (8 * 8)
row_start = cuda.blockIdx.x
col_start = cuda.blockIdx.y
tx = cuda.threadIdx.x
row_size = min((N - (row_start... |
class ProxyMixin(object):
def get_proxied(self):
return self.inner
def is_proxy(self):
return True
def get_properties(self):
return self.properties
def get_property(self, prop, default=None):
if (self.properties is None):
return default
return self.pro... |
def validate_conf(*args, **kwargs):
config = ConfFile(*args, **kwargs)
is_config_ok = True
try:
config.pyms
except AttrDoesNotExistException:
is_config_ok = False
if (not is_config_ok):
raise ConfigErrorException('Config file must start with `pyms` keyword, for example:\n ... |
class LosDialog(QtWidgets.QDialog):
def __init__(self, sandbox, *args, **kwargs):
QtWidgets.QDialog.__init__(self, *args, **kwargs)
loadUi(get_resource('dialog_los.ui'), self)
self.setSizeGripEnabled(False)
self.move((self.parent().window().mapToGlobal(self.parent().window().rect().c... |
class TestPortaraDataProviderIntraday(TestCase):
def setUpClass(cls) -> None:
cls.start_date = datetime(2021, 6, 11, 17, 13)
cls.end_date = datetime(2021, 6, 14, 8, 46)
cls.number_of_data_bars = 29
cls.fields = PriceField.ohlcv()
cls.ticker = PortaraTicker('AB', SecurityType.... |
class EarleyRegexpMatcher():
def __init__(self, lexer_conf):
self.regexps = {}
for t in lexer_conf.terminals:
regexp = t.pattern.to_regexp()
try:
width = get_regexp_width(regexp)[0]
except ValueError:
raise GrammarError(('Bad regexp... |
class Tab():
def __init__(self, view, title, tab_key, contents_factory):
self.title = title
self.tab_key = tab_key
self.contents_factory = contents_factory
self.view = view
self.panel = None
self.menu_item = None
def get_bookmark(self, view):
return view.a... |
class Gaussian(object):
def __init__(self, mu, rho):
super().__init__()
self.mu = mu
self.rho = rho
self.normal = torch.distributions.Normal(0, 1)
def sigma(self):
return F.softplus(self.rho, beta=1)
def sample(self, stochastic=False, return_log_prob=False):
w... |
class TypeHexagonSymmetry(Enum):
(R60, R120, R180, R240, R300, L1, L2, L3, L4, L5, L6) = auto(11)
def rotations():
return (TypeHexagonSymmetry.R60, TypeHexagonSymmetry.R120, TypeHexagonSymmetry.R180, TypeHexagonSymmetry.R240, TypeHexagonSymmetry.R300)
def reflections():
return (TypeHexagonSy... |
def test_config_pickling():
root = configdefaults.config
buffer = io.BytesIO()
pickle.dump(root, buffer)
buffer.seek(0)
restored = pickle.load(buffer)
for name in root._config_var_dict.keys():
v_original = getattr(root, name)
v_restored = getattr(restored, name)
assert (v... |
def run_simulation(model, time=10000, points=200, cleanup=True, output_prefix=None, output_dir=None, flux_map=False, perturbation=None, seed=None, verbose=False):
warnings.warn('run_simulation will be removed in a future version of PySB. Use pysb.simulator.KappaSimulator instead.', DeprecationWarning)
gen = Kap... |
class TestFlatLayoutPackageFinder():
EXAMPLES = {'hidden-folders': (['.pkg/__init__.py', 'pkg/__init__.py', 'pkg/nested/file.txt'], ['pkg', 'pkg.nested']), 'private-packages': (['_pkg/__init__.py', 'pkg/_private/__init__.py'], ['pkg', 'pkg._private']), 'invalid-name': (['invalid-pkg/__init__.py', 'other.pkg/__init_... |
def main() -> None:
if ((len(sys.argv) > 1) and (sys.argv[1] in ('run', 'test'))):
manager = SiteManager(sys.argv)
if (sys.argv[1] == 'run'):
manager.run_server()
elif (sys.argv[1] == 'test'):
manager.run_tests()
else:
_static_build = ((len(sys.argv) > 1) ... |
_HEADS_REGISTRY.register()
class BBoxIOUTracker(BaseTracker):
def __init__(self, *, video_height: int, video_width: int, max_num_instances: int=200, max_lost_frame_count: int=0, min_box_rel_dim: float=0.02, min_instance_period: int=1, track_iou_threshold: float=0.5, **kwargs):
super().__init__(**kwargs)
... |
class TestFDCapture():
def test_simple(self, tmpfile: BinaryIO) -> None:
fd = tmpfile.fileno()
cap = capture.FDCapture(fd)
data = b'hello'
os.write(fd, data)
pytest.raises(AssertionError, cap.snap)
cap.done()
cap = capture.FDCapture(fd)
cap.start()
... |
def main():
maxiters = 300
DE_class = calc_min_Jsc()
PDE_obj = PDE(DE_class.evaluate, bounds=[[10, 150], [10, 105], [200, 1000], [500, 10000], [500, 10000]], maxiters=maxiters)
res = PDE_obj.solve()
best_pop = res[0]
print('parameters for best result:', best_pop, '\n', 'optimized Jsc value (mA/c... |
def regex_match(text, pattern):
try:
pattern = re.compile(pattern, flags=((re.IGNORECASE + re.UNICODE) + re.MULTILINE))
except BaseException:
print(('Regular expression failed to compile: %s' % pattern))
return []
matched = [x.group() for x in re.finditer(pattern, text)]
return l... |
def get_xwayland_atoms(xwayland: xwayland.XWayland) -> dict[(int, str)]:
xwayland_wm_types = {'_NET_WM_WINDOW_TYPE_DESKTOP': 'desktop', '_NET_WM_WINDOW_TYPE_DOCK': 'dock', '_NET_WM_WINDOW_TYPE_TOOLBAR': 'toolbar', '_NET_WM_WINDOW_TYPE_MENU': 'menu', '_NET_WM_WINDOW_TYPE_UTILITY': 'utility', '_NET_WM_WINDOW_TYPE_SPL... |
class _UsageKind(enum.IntEnum):
unused = 1
used_in_test = 2
used = 3
def classify(cls, module_name: str) -> '_UsageKind':
if ('.' not in module_name):
return cls.used
own_name = module_name.rsplit('.', maxsplit=1)[1]
if own_name.startswith('test'):
return ... |
def test_hierarchical_obs_logp():
obs = np.array([0.5, 0.4, 5, 2])
with pm.Model() as model:
x = pm.Uniform('x', 0, 1, observed=obs)
pm.Uniform('y', x, 2, observed=obs)
logp_ancestors = list(ancestors([model.logp()]))
ops = {a.owner.op for a in logp_ancestors if a.owner}
assert (len(... |
class OpenMM(Engines):
def __init__(self, molecule, pdb_file=None, xml_file=None):
super().__init__(molecule)
self.pdb_file = (pdb_file or f'{molecule.name}.pdb')
self.xml_file = (xml_file or f'{molecule.name}.xml')
self.system = None
self.simulation = None
self.creat... |
class Request(object):
headers = {'User-Agent': 'Mozilla/5.0 (X11; U; Linux i686; ru; rv:1.9.1.8) Gecko/ Linux Mint/8 (Helena) Firefox/3.5.8', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'ru,en-us;q=0.7,en;q=0.3', 'Accept-Encoding': 'deflate', 'Accept-Charset': 'w... |
class NoOpOptimizer(torch.optim.Optimizer):
def __init__(self, params, defaults):
torch._C._log_api_usage_once('python.optimizer')
self.defaults = defaults
self._hook_for_profile()
if isinstance(params, torch.Tensor):
raise TypeError(('params argument given to the optimiz... |
class StoryboardElementStateCondition(_ValueTriggerType):
def __init__(self, element, reference, state):
self.element = convert_enum(element, StoryboardElementType)
self.reference = reference
self.state = convert_enum(state, StoryboardElementState)
def __eq__(self, other):
if isi... |
class AddressBookPanel(Div):
def __init__(self, view, address_book_ui):
super().__init__(view)
self.rows = self.initialise_rows()
self.add_child(H(view, 1, text='Addresses'))
form = self.add_child(Form(view, 'address_table_form'))
self.define_event_handler(self.events.delete_... |
class CmdDrop(MuxCommand):
key = 'drop'
locks = 'cmd:all()'
arg_regex = '\\s|$'
def func(self):
caller = self.caller
if (not self.args):
caller.msg('Drop what?')
return
obj = caller.search(self.args, location=caller, nofound_string=("You aren't carrying %s... |
class ReadBitsRequestBase(ModbusRequest):
_rtu_frame_size = 8
def __init__(self, address, count, slave=0, **kwargs):
ModbusRequest.__init__(self, slave, **kwargs)
self.address = address
self.count = count
def encode(self):
return struct.pack('>HH', self.address, self.count)
... |
class resnet(torch.nn.Module):
def __init__(self, requires_grad=False, pretrained=True, num=18):
super(resnet, self).__init__()
if (num == 18):
self.net = models.resnet18(pretrained=pretrained)
elif (num == 34):
self.net = models.resnet34(pretrained=pretrained)
... |
class CILogonOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.cilogon.CILogonOAuth2'
user_data_url = '
user_data_url_post = True
expected_username = ''
access_token_body = json.dumps({'access_token': ' 'refresh_token': ' 'id_token': 'aBigStringOfRandomChars.123abc', 'token_type': 'Bearer... |
.parametrize('strict', [False, True])
def test_loading(strict):
assert (msgspec.convert(create_dumped_response(), GetRepoIssuesResponse, strict=strict) == create_response(GetRepoIssuesResponse, Issue, Reactions, PullRequest, Label, SimpleUser))
assert (msgspec.convert(create_dumped_response(), GetRepoIssuesResp... |
class CardUser(QWidget, Ui_CardUser):
emitDisableUser = pyqtSignal(User)
emitDeleteUser = pyqtSignal(User)
emitEditUser = pyqtSignal(User)
def __init__(self, user):
super(CardUser, self).__init__()
self.setupUi(self)
self.user = user
self.settings = QSettings(zapzap.__app... |
def test_precmd_hook_emptystatement_first(capsys):
app = PluggedApp()
app.register_precmd_hook(app.precmd_hook_emptystatement)
stop = app.onecmd_plus_hooks('say hello')
(out, err) = capsys.readouterr()
assert (not stop)
assert (not out)
assert (not err)
assert (app.called_precmd == 1)
... |
class TestTrainingExtensionsTensorReduction(unittest.TestCase):
def test_tensor_reduction(self):
shape = [3, 2, 4]
tensor = torch.zeros(shape, dtype=torch.int8)
view = tensor.reshape([(- 1)])
for i in range(tensor.numel()):
view[i] = (101 + i)
reduct = PolySlice(d... |
class ParallelMaxxVitBlock(nn.Module):
def __init__(self, dim, dim_out, stride=1, num_conv=2, conv_cfg: MaxxVitConvCfg=MaxxVitConvCfg(), transformer_cfg: MaxxVitTransformerCfg=MaxxVitTransformerCfg(), drop_path=0.0):
super().__init__()
conv_cls = (ConvNeXtBlock if (conv_cfg.block_type == 'convnext')... |
_criterion('ctc', dataclass=CtcCriterionConfig)
class CtcCriterion(FairseqCriterion):
def __init__(self, cfg: CtcCriterionConfig, task: FairseqTask):
super().__init__(task)
self.blank_idx = (task.target_dictionary.index(task.blank_symbol) if hasattr(task, 'blank_symbol') else 0)
self.pad_idx... |
.usefixtures('_force_blank_two_way')
def test_distribute_pre_fill_weaknesses_swap_force_two_way(empty_patches):
rng = Random(10000)
patches = dataclasses.replace(empty_patches, configuration=dataclasses.replace(empty_patches.configuration, dock_rando=dataclasses.replace(empty_patches.configuration.dock_rando, m... |
_db
def test_query_single_page(rf, graphql_client):
request = rf.get('/')
page = PageFactory(slug=LazyI18nString({'en': 'demo'}), published=True, image=None, conference__code='pycon11')
resp = graphql_client.query('query {\n page(code: "pycon11", slug: "demo") {\n id\n ... |
def assert_source_added(tester: CommandTester, poetry: Poetry, source_existing: Source, source_added: Source) -> None:
assert (tester.io.fetch_output().strip() == f'Adding source with name {source_added.name}.')
poetry.pyproject.reload()
sources = poetry.get_sources()
assert (sources == [source_existing... |
def safe_join(t: Type, s: Type) -> Type:
if ((not isinstance(t, UnpackType)) and (not isinstance(s, UnpackType))):
return join_types(t, s)
if (isinstance(t, UnpackType) and isinstance(s, UnpackType)):
return UnpackType(join_types(t.type, s.type))
return object_or_any_from_type(get_proper_typ... |
def test_rcs_bistatic():
phi = np.array([(- 30), (- 24), 65])
theta = 90
inc_phi = 30
inc_theta = 90
freq = .0
pol = np.array([0, 0, 1])
density = 1
rcs = np.zeros_like(phi)
target = {'model': './models/plate5x5.stl', 'location': (0, 0, 0)}
for (phi_idx, phi_ang) in enumerate(phi... |
class TestOnlineContrastiveLoss():
embeddings = torch.Tensor([[0.0, (- 1.0), 0.5], [0.1, 2.0, 0.5], [0.0, 0.3, 0.2], [1.0, 0.0, 0.9], [1.2, (- 1.2), 0.01], [(- 0.7), 0.0, 1.5]])
groups = torch.LongTensor([1, 2, 3, 3, 2, 1])
def test_batch_all(self):
loss = OnlineContrastiveLoss(mining='all')
... |
class EncodeProcessDecode(nn.Module):
def __init__(self, output_size, latent_size, num_layers, message_passing_aggregator, message_passing_steps, attention, ripple_used, ripple_generation=None, ripple_generation_number=None, ripple_node_selection=None, ripple_node_selection_random_top_n=None, ripple_node_connection... |
def _create_parametrization(data: list[str]) -> dict[(str, Path)]:
id_to_kwargs = {}
for (data_name, kwargs) in data.items():
id_to_kwargs[data_name] = {'path_to_input_data': path_to_input_data(data_name), 'path_to_processed_data': path_to_processed_data(data_name), **kwargs}
return id_to_kwargs |
def add_testvalue_and_checking_configvars():
config.add('print_test_value', "If 'True', the __eval__ of an PyTensor variable will return its test_value when this is available. This has the practical consequence that, e.g., in debugging `my_var` will print the same as `my_var.tag.test_value` when a test value is def... |
def test_run_pyscript_stop(base_app, request):
test_dir = os.path.dirname(request.module.__file__)
python_script = os.path.join(test_dir, 'pyscript', 'help.py')
stop = base_app.onecmd_plus_hooks('run_pyscript {}'.format(python_script))
assert (not stop)
python_script = os.path.join(test_dir, 'pyscri... |
def test_project_issue_label_events(project, resp_project_issue_label_events):
issue = project.issues.list()[0]
label_events = issue.resourcelabelevents.list()
assert isinstance(label_events, list)
label_event = label_events[0]
assert isinstance(label_event, ProjectIssueResourceLabelEvent)
asser... |
def deser_compact_size(f) -> Optional[int]:
try:
nit = f.read(1)[0]
except IndexError:
return None
if (nit == 253):
nit = struct.unpack('<H', f.read(2))[0]
elif (nit == 254):
nit = struct.unpack('<I', f.read(4))[0]
elif (nit == 255):
nit = struct.unpack('<Q', ... |
class TestInstall():
def test_real_profile(self):
profile = QWebEngineProfile()
cookies.install_filter(profile)
def test_fake_profile(self, stubs):
store = stubs.FakeCookieStore()
profile = stubs.FakeWebEngineProfile(cookie_store=store)
cookies.install_filter(profile)
... |
def test_crop_item(item):
item.crop = QtCore.QRectF(0, 0, 100, 80)
command = commands.CropItem(item, QtCore.QRectF(10, 20, 30, 40))
command.redo()
assert (item.crop == QtCore.QRectF(10, 20, 30, 40))
assert (item.pos() == QtCore.QPointF(0, 0))
command.undo()
assert (item.crop == QtCore.QRectF... |
def set_default_units(system=None, currency=None, current=None, information=None, length=None, luminous_intensity=None, mass=None, substance=None, temperature=None, time=None):
if (system is not None):
system = system.lower()
try:
assert (system in ('si', 'cgs'))
except Assertion... |
.end_to_end()
def test_task_function_with_partialed_args_and_task_decorator(tmp_path, runner):
source = '\n from pytask import task\n import functools\n from pathlib import Path\n\n def func(content):\n return content\n\n task_func = task(produces=Path("out.txt"))(\n functools.partial(f... |
def test_tpdm_opdm_mapping():
db = tpdm_to_opdm_mapping(6, (1 / 2))
for dbe in db:
assert isinstance(dbe, DualBasisElement)
assert (set(dbe.primal_tensors_names) == {'cckk', 'ck'})
assert ((len(dbe.primal_elements) == 7) or (len(dbe.primal_elements) == 14))
assert np.isclose(dbe.... |
def test_log_file_cli_level(pytester: Pytester) -> None:
pytester.makepyfile('\n import pytest\n import logging\n def test_log_file(request):\n plugin = request.config.pluginmanager.getplugin(\'logging-plugin\')\n assert plugin.log_file_handler.level == logging.INFO\n ... |
class Solution():
def __init__(self):
self.list = []
def postorderTraversal(self, root: TreeNode) -> List[int]:
if root:
self.postorderTraversal(root.left)
self.postorderTraversal(root.right)
if root.val:
self.list.append(root.val)
retu... |
class Trainer(object):
def __init__(self, cfg_trainer, model, optimizer, train_loader, test_loader, lr_scheduler, bnm_scheduler, logger):
self.cfg = cfg_trainer
self.model = model
self.optimizer = optimizer
self.train_loader = train_loader
self.test_loader = test_loader
... |
class mysql(object):
host = (mysql_url.hostname or 'localhost')
port = (mysql_url.port or '3306')
database = (mysql_url.path[1:] or 'qd')
user = (mysql_url.username or 'qd')
passwd = (mysql_url.password or None)
auth_plugin = parse_qs(mysql_url.query).get('auth_plugin', [''])[0] |
_fixtures(WebFixture, WidgetCreationScenarios)
def test_widget_factory_creates_widget_with_layout(web_fixture, widget_creation_scenarios):
class MyLayout(Layout):
def customise_widget(self):
self.widget.add_child(P(self.view, text='This widget is using Mylayout'))
layout_for_widget = MyLayou... |
_fixtures(WebFixture, CarouselFixture)
def test_active_state_of_items(web_fixture, carousel_fixture):
fixture = carousel_fixture
carousel = Carousel(web_fixture.view, 'my_carousel_id')
carousel.add_slide(Img(web_fixture.view))
carousel.add_slide(Img(web_fixture.view))
main_div = fixture.get_main_div... |
def segmentation():
court_top_left_x = 470
court_top_left_y = 127
court_top_right_x = 895
court_top_right_y = 127
court_down_left_x = 276
court_down_left_y = 570
court_down_right_x = 1000
court_down_right_y = 570
hitpoint = [0 for _ in range(len(df['vecY']))]
for i in range(2, (l... |
def invert(g_ema, perceptual, real_img, device, args):
save = args.save
result = {}
to_vgg = TO_VGG()
requires_grad(perceptual, True)
requires_grad(g_ema, True)
log_size = int(math.log(256, 2))
num_layers = (((log_size - 2) * 2) + 1)
w = args.mean_w.clone().detach().to(device).unsqueeze(... |
def test_expression_not_string(temp_dir):
source = CodeSource(str(temp_dir), {'path': 'a/b.py', 'expression': 23})
file_path = ((temp_dir / 'a') / 'b.py')
file_path.ensure_parent_dir_exists()
file_path.touch()
with pytest.raises(TypeError, match='option `expression` must be a string'):
sourc... |
class _RequestCounter():
exp_cnt: int
_keys: List[str] = ['limit', 'pause', 'reset_epoch', 'resume']
_cnt: Dict[(str, int)]
_reached: Dict[(str, bool)]
def __init__(self, exp_cnt: int):
self.exp_cnt = exp_cnt
self._cnt = {k: 0 for k in self._keys}
self._reached = {k: False fo... |
class MatchesReraisedExcInfo(object):
expected = attr.ib()
def match(self, actual):
valcheck = Equals(self.expected.args).match(actual.args)
if (valcheck is not None):
return valcheck
typecheck = Equals(type(self.expected)).match(type(actual))
if (typecheck is not Non... |
class CharacterListView(LoginRequiredMixin, CharacterMixin, ListView):
template_name = 'website/character_list.html'
paginate_by = 100
page_title = 'Character List'
access_type = 'view'
def get_queryset(self):
account = self.request.user
ids = [obj.id for obj in self.typeclass.object... |
def train(args, model, device, train_loader, optimizer, epoch):
model.train()
criterion = nn.BCELoss()
for (batch_idx, (images_1, images_2, targets)) in enumerate(train_loader):
(images_1, images_2, targets) = (images_1.to(device), images_2.to(device), targets.to(device))
optimizer.zero_grad... |
class TestEvaluate(TestCase):
def test_find_symbols(self):
a = pybamm.StateVector(slice(0, 1))
b = pybamm.StateVector(slice(1, 2))
constant_symbols = OrderedDict()
variable_symbols = OrderedDict()
expr = (a + b)
pybamm.find_symbols(expr, constant_symbols, variable_sym... |
def get_logger(filename=None):
logger = logging.getLogger('logger')
logger.setLevel(logging.DEBUG)
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO)
if (filename is not None):
handler = logging.FileHandler(filename)
... |
def _object_search_select(caller, obj_entry, **kwargs):
choices = kwargs['available_choices']
num = choices.index(obj_entry)
matches = caller.ndb._menutree.olc_search_object_matches
obj = matches[num]
if (not obj.access(caller, 'examine')):
caller.msg("|rYou don't have 'examine' access on th... |
class RGBEncoder(nn.Module):
def __init__(self):
super().__init__()
resnet = mod_resnet.resnet50(pretrained=True)
self.conv1 = resnet.conv1
self.bn1 = resnet.bn1
self.relu = resnet.relu
self.maxpool = resnet.maxpool
self.res2 = resnet.layer1
self.layer... |
class CPD_ResNet(nn.Module):
def __init__(self, channel=32):
super(CPD_ResNet, self).__init__()
self.resnet = B2_ResNet()
self.rfb2_1 = RFB(512, channel)
self.rfb3_1 = RFB(1024, channel)
self.rfb4_1 = RFB(2048, channel)
self.agg1 = aggregation(channel)
self.rf... |
def test_rate_limits(gl):
settings = gl.settings.get()
settings.throttle_authenticated_api_enabled = True
settings.throttle_authenticated_api_requests_per_period = 1
settings.throttle_authenticated_api_period_in_seconds = 3
settings.save()
projects = []
for i in range(0, 20):
project... |
def MaximumArg(term, *others, rank=None, condition=None):
terms = _extremum_terms(term, others)
checkType(rank, (type(None), TypeRank))
c = ConstraintMaximumArg(terms, rank, condition)
return (_wrapping_by_complete_or_partial_constraint(c) if isinstance(c, ConstraintMaximumArg) else c) |
class _AdditionalInformationPredict():
def __init__(self, directory, xml_file, method_name, model_type=('classification', None)):
self.directory = directory
self.xml_file = xml_file
self.method_name = method_name
self.model_type = model_type
self.result_filename = os.path.joi... |
def test__optimal_time_ocp__multiphase_time_constraint():
from bioptim.examples.optimal_time_ocp import multiphase_time_constraint as ocp_module
bioptim_folder = os.path.dirname(ocp_module.__file__)
final_time = (2, 5, 4)
time_min = (1, 3, 0.1)
time_max = (2, 4, 0.8)
ns = (20, 30, 20)
ocp_mo... |
def test_run_with_dependencies_nested_extras(installer: Installer, locker: Locker, repo: Repository, package: ProjectPackage) -> None:
package_a = get_package('A', '1.0')
package_b = get_package('B', '1.0')
package_c = get_package('C', '1.0')
dependency_c = Factory.create_dependency('C', {'version': '^1... |
()
def skip_userid_validation(monkeypatch):
import raiden.network.transport.matrix
import raiden.network.transport.matrix.utils
def mock_validate_userid_signature(user):
return factories.HOP1
monkeypatch.setattr(raiden.network.transport.matrix, 'validate_userid_signature', mock_validate_userid_s... |
class ModelCompressor():
def compress_model(model: tf.keras.Model, eval_callback: EvalFunction, eval_iterations, compress_scheme: CompressionScheme, cost_metric: CostMetric, parameters: Union[SpatialSvdParameters], trainer: Callable=None, visualization_url: str=None) -> Tuple[(tf.keras.Model, CompressionStats)]:
... |
def rewrite_dyld_path(dylib: Path):
def _read_until_zero(fp):
cur = fp.tell()
s = b''
ch = fp.read(1)
while ((ch != b'\x00') and (ch != b'')):
s += ch
ch = fp.read(1)
fp.seek(cur, 0)
return s.decode('utf-8')
def _parse_libr_name(path):
... |
_module()
class Res2Net(ResNet):
arch_settings = {50: (Bottle2neck, (3, 4, 6, 3)), 101: (Bottle2neck, (3, 4, 23, 3)), 152: (Bottle2neck, (3, 8, 36, 3))}
def __init__(self, scales=4, base_width=26, style='pytorch', deep_stem=True, avg_down=True, **kwargs):
self.scales = scales
self.base_width = b... |
class MsgSensors():
def __init__(self):
self.gyro_x = 0
self.gyro_y = 0
self.gyro_z = 0
self.accel_x = 0
self.accel_y = 0
self.accel_z = 0
self.mag_x = 0
self.mag_y = 0
self.mag_z = 0
self.abs_pressure = 0
self.diff_pressure = 0... |
class Graph(object):
def __init__(self, idx, num_nodes):
self.g_id = idx
self.num_nodes = num_nodes
self.node = []
def add_node(self, one_node):
self.node.append(one_node)
def neighbors(self, idx):
return self.node[idx].neighbors
def ins(self, idx):
return... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.