code stringlengths 281 23.7M |
|---|
def make_connection(wire_nodes, wire1, wire2):
if (wire_nodes[wire1] is wire_nodes[wire2]):
assert (wire1 in wire_nodes[wire1])
assert (wire2 in wire_nodes[wire2])
return
new_node = (wire_nodes[wire1] | wire_nodes[wire2])
for wire in new_node:
wire_nodes[wire] = new_node |
def parse_host_file(fpath):
lines = __read_from_file(fpath)
results = []
for line in lines:
find = line.find(':')
if (find < 1):
raise FilefmtErr(('wrong host_rule content %s' % line))
a = line[0:find]
e = (find + 1)
try:
b = int(line[e:])
... |
class Snackbar(Component):
css_classes = ['mdc-snackbar', 'mdc-snackbar--open']
name = 'Material Design Snackbar'
str_repr = '\n<aside {attrs}>\n <div class="mdc-snackbar__surface" role="status" aria-relevant="additions">\n <div class="mdc-snackbar__label" aria-atomic="false">\n Can\'t send photo. ... |
class SensorsFansCommandHandler(MethodCommandHandler):
def __init__(self) -> None:
super().__init__('sensors_fans')
return
def handle(self, params: str) -> Payload:
tup = self.get_value()
assert isinstance(tup, dict)
(source, param) = split(params)
if ((source == ... |
def test_local_module() -> None:
dependencies: list[Dependency] = []
modules_locations = [ModuleLocations(ModuleBuilder('foobar', {'foo', 'foobar'}, frozenset(), dependencies).build(), [Location(Path('foo.py'), 1, 2)])]
assert (DEP001MissingDependenciesFinder(modules_locations, dependencies).find() == []) |
def extractHaneulXBadaTumblrCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) ... |
class TestBasicBuilder():
def test_raise_tuner_sample(self, monkeypatch, tmp_path):
with monkeypatch.context() as m:
m.setattr(sys, 'argv', ['', '--config', './tests/conf/yaml/test.yaml'])
config = ConfigArgBuilder(*all_configs, desc='Test Builder')
now = datetime.datetim... |
_required
def activity_proposal(request, event_slug):
event = get_object_or_404(Event, event_slug=event_slug)
if (not event.activity_proposal_is_open):
messages.error(request, _('The activity proposal is already closed or the event is not accepting proposals through this page.... |
def get_global_radix_info(size):
assert (size == (2 ** helpers.log2(size)))
base_radix = min(size, 128)
num_radices = 0
while (size > base_radix):
size //= base_radix
num_radices += 1
radix_list = (([base_radix] * num_radices) + [size])
radix1_list = []
radix2_list = []
f... |
def git_clone(url, dstpath, branch):
debug_print((((('git_clone(url=' + url) + ', dstpath=') + dstpath) + ')'))
if os.path.isdir(os.path.join(dstpath, '.git')):
debug_print((((("Repository '" + url) + "' already cloned to directory '") + dstpath) + "', skipping."))
return True
mkdir_p(dstpat... |
class TestNestedSlugRelatedField(APISimpleTestCase):
def setUp(self):
self.queryset = MockQueryset([MockObject(pk=1, name='foo', nested=MockObject(pk=2, name='bar', nested=MockObject(pk=7, name='foobar'))), MockObject(pk=3, name='hello', nested=MockObject(pk=4, name='world', nested=MockObject(pk=8, name='he... |
def test_wrapped_tasks_error(capfd):
subprocess.run([sys.executable, str((test_module_dir / 'simple_decorator.py'))], env={'SCRIPT_INPUT': '0', 'SYSTEMROOT': 'C:\\Windows', 'HOMEPATH': 'C:\\Windows'}, text=True)
out = capfd.readouterr().out
assert (out.replace('\r', '').strip().split('\n')[:5] == ['before r... |
def check_userdoc(contract_name: str, data: Dict[(str, Any)], warnings: Dict[(str, str)]) -> Dict[(str, str)]:
if (('userdoc' not in data) or (not data['userdoc'])):
return assoc_in(warnings, ['contractTypes', contract_name, 'userdoc'], WARNINGS['userdoc_missing'].format(contract_name))
return warnings |
class Entity():
def __init__(self, name, externally_visible=False):
assert isinstance(name, str)
assert isinstance(externally_visible, bool)
self.name = name
self.is_externally_visible = externally_visible
def dump(self):
raise ICE('dump is not defined') |
def test_checker_simple():
warnings = check_manifest({})
assert (warnings == {'manifest': "Manifest missing a required 'manifest' field.", 'name': "Manifest missing a suggested 'name' field", 'version': "Manifest missing a suggested 'version' field.", 'meta': "Manifest missing a suggested 'meta' field.", 'sourc... |
class PostgresSearchBackend(SearchBackend):
search_config = getattr(settings, 'WATSON_POSTGRES_SEARCH_CONFIG', 'pg_catalog.english')
def escape_postgres_query(self, text):
return ' & '.join(('$${0}$$:*'.format(word) for word in escape_query(text, RE_POSTGRES_ESCAPE_CHARS).split()))
def is_installed(... |
class TestArchChecker_1(TestArchChecker):
def test_significantlySimilar_1(self):
cwd = os.path.dirname(os.path.realpath(__file__))
ck = TestArchiveChecker('{cwd}/test_ptree/notQuiteAllArch.zip'.format(cwd=cwd))
ret = ck.getSignificantlySimilarArches(searchDistance=2)
expect = {5: ['{... |
class OptionPlotoptionsOrganizationLevelsStatesInactive(Options):
def animation(self) -> 'OptionPlotoptionsOrganizationLevelsStatesInactiveAnimation':
return self._config_sub_data('animation', OptionPlotoptionsOrganizationLevelsStatesInactiveAnimation)
def enabled(self):
return self._config_get(... |
class Tree(object):
def __init__(self):
self.outmost = Root('')
self.stack = deque()
self.stack.append(self.outmost)
def clear(self):
self.outmost = Root('')
self.stack.clear()
self.stack.append(self.outmost)
def last(self):
return self.stack[(- 1)]
... |
(IHeadingText)
class HeadingText(MHeadingText, LayoutWidget):
def _create_control(self, parent):
control = QtGui.QLabel(parent)
control.setSizePolicy(QtGui.QSizePolicy.Policy.Preferred, QtGui.QSizePolicy.Policy.Fixed)
return control
def _set_control_text(self, text):
text = f'<b>... |
def reverse_app(parser, token):
bits = token.split_contents()
if (len(bits) < 3):
raise TemplateSyntaxError("'reverse_app' takes at least two arguments, a namespace and a URL pattern name.")
namespaces = parser.compile_filter(bits[1])
viewname = parser.compile_filter(bits[2])
args = []
k... |
()
def edit_observation(observation, data_type, result):
observation_doc = frappe.get_doc('Observation', observation)
if (data_type in ['Range', 'Ratio', 'Quantity', 'Numeric']):
observation_doc.result_data = result
elif (data_type == 'Text'):
observation_doc.result_text = result
observa... |
class MemberAccess(Expression, LValueMixin):
expression: Expression
member_name: str
base_expression_cfg = synthesized()
base_expression_value = synthesized()
def base_expression_value(self, expression):
return expression.expression_value
def base_expression_cfg(self, expression):
... |
class bolt_checkpoint(write_checkpoint):
_DEFAULT_REGISTRY_KEY = 'bolt_checkpoint_key'
_PARAMS_CONTAINING_INSTANCE_ID = ['instance_id', 'publisher_id', 'partner_id', 'job', 'instance_args', 'injection_args']
_DEFAULT_COMPONENT_NAME = 'Bolt'
def _param_to_instance_id(cls, instance_id_param: str, kwargs: ... |
def parse_get_repository_response(resp: Dict[(str, Any)], downloaded_at: date) -> Repository:
return Repository(name=resp['full_name'], short_name=resp.get('name', ''), language=resp.get('language'), license=(resp.get('license').get('key') if isinstance(resp.get('license'), dict) else None), is_fork=resp.get('fork'... |
_grad()
def test_encode_decode(encoder: LatentDiffusionAutoencoder, sample_image: Image.Image):
encoded = encoder.encode_image(sample_image)
decoded = encoder.decode_latents(encoded)
assert (decoded.mode == 'RGB')
assert (max(iter(decoded.getdata(band=1))) < 255)
ensure_similar_images(sample_image, ... |
def exposed_delete_gravitytales_bot_blocked_pages():
with db.session_context() as sess:
tables = [db.WebPages.__table__, version_table(db.WebPages.__table__)]
for ctbl in tables:
update = ctbl.delete().where((ctbl.c.netloc == 'gravitytales.com')).where(ctbl.c.content.like('%<div id="bot-... |
class ExpandablePanel(LayoutWidget):
STYLE = wx.CLIP_CHILDREN
collapsed_image = Image(ImageResource('mycarat1'))
expanded_image = Image(ImageResource('mycarat2'))
_layers = Dict(Str)
_headers = Dict(Str)
def __init__(self, parent=None, **traits):
create = traits.pop('create', None)
... |
class TestWorkflowExecutionRpc(BaseUnitTest):
def setUp(self) -> None:
super().setUp()
with mock.patch('ai_flow.task_executor.common.task_executor_base.HeartbeatManager'):
with mock.patch('ai_flow.rpc.service.scheduler_service.get_notification_client', MockNotificationClient):
... |
class OptionSeriesWaterfallSonificationDefaultinstrumentoptionsMappingPan(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str)... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = None
fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_path': {... |
def int2c2e3d_14(ax, da, A, bx, db, B):
result = numpy.zeros((3, 15), dtype=float)
x0 = (ax + bx)
x1 = (x0 ** (- 1.0))
x2 = ((- x1) * ((ax * A[0]) + (bx * B[0])))
x3 = ((- x2) - A[0])
x4 = ((- x2) - B[0])
x5 = (bx ** (- 1.0))
x6 = (ax * x1)
x7 = ((bx * x6) * ((((A[0] - B[0]) ** 2) + ... |
def test_multiaddr_from_string():
maddr_str = (((('/dns4/' + HOST) + '/tcp/') + str(PORT)) + '/p2p/')
maddr = MultiAddr.from_string((maddr_str + PEER_ID))
assert ((maddr.host == HOST) and (maddr.port == PORT) and (maddr.peer_id == PEER_ID))
with pytest.raises(ValueError):
MultiAddr.from_string('... |
class CliBoundArguments(object):
threshold = 0.75
sig = attr.ib()
in_args: typing.Tuple = attr.ib(converter=tuple)
name = attr.ib()
func = attr.ib(default=None)
post_name = attr.ib(default=attr.Factory(list))
args = attr.ib(default=attr.Factory(list))
kwargs = attr.ib(default=attr.Factor... |
class Rule(object):
def __init__(self, rule_name, rule_index, rules):
self.rule_name = rule_name
self.rule_index = rule_index
self.rules = rules
def find_violations(self, cloudsql_acl):
if (not cloudsql_acl.ipv4_enabled):
return
is_instance_name_violated = Tru... |
.parametrize('mat_type', ['nest', 'aij'])
.parametrize('scalar', [False, True], ids=['Vector', 'Scalar'])
def test_partially_mixed_mat(V, Q, mat_type, scalar):
W = (V * Q)
(u, p) = TrialFunctions(W)
if scalar:
v = TestFunction(V)
a = (inner(u, v) * dx)
idx = (0, 0)
other = (0... |
class TestRestrictedNamedTraitObserverWithWrappedObserver(unittest.TestCase):
def test_notify_inherited(self):
wrapped_observer = DummyObserver(notify=False)
observer = _RestrictedNamedTraitObserver(name='name', wrapped_observer=wrapped_observer)
self.assertEqual(observer.notify, wrapped_obs... |
class OptionPlotoptionsLollipopSonificationDefaultinstrumentoptionsMappingLowpass(Options):
def frequency(self) -> 'OptionPlotoptionsLollipopSonificationDefaultinstrumentoptionsMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsLollipopSonificationDefaultinstrumentoptionsMa... |
.django_db
def test_parent_recipient_preference_to_uei(recipient_lookup):
recipient_parameters = {'recipient_name': 'Parent Recipient Test', 'recipient_uei': '123', 'parent_recipient_uei': None, 'recipient_unique_id': 'NOT A REAL DUNS', 'parent_recipient_unique_id': None, 'is_parent_recipient': True}
expected_r... |
class TestExpressions():
def test_special(self):
assert (py2js('') == '')
assert (py2js(' \n') == '')
def test_ops(self):
assert (py2js('2+3') == '2 + 3;')
assert (py2js('2/3') == '2 / 3;')
assert (py2js('not 2') == '!2;')
assert (py2js('-(2+3)') == '-(2 + 3);')
... |
class LocalTrack(LocalItem):
album: LocalAlbum
artists: List[LocalArtist]
available_markets: List[None]
disc_number: int
duration_ms: Union[(int, dict)]
explicit: bool
external_ids: dict
external_urls: dict
is_local: Literal[True]
popularity: int
preview_url: None
track_n... |
class PlaySourceShowingPolicy(GObject.Object):
def __init__(self, list_view):
super(PlaySourceShowingPolicy, self).__init__()
self.counter = 0
self._has_initialised = False
def initialise(self, album_manager):
if self._has_initialised:
return
self._has_initial... |
def to_case_block(c: Case) -> Tuple[(Union[_core_wf.IfBlock], typing.List[Promise])]:
(expr, promises) = transform_to_boolexpr(cast(Union[(ComparisonExpression, ConjunctionExpression)], c.expr))
if (c.output_promise is not None):
n = c.output_node
return (_core_wf.IfBlock(condition=expr, then_node=n... |
class UDisksDBusWrapper():
__slots__ = ['obj', 'iface_type', '_iface', '_props_iface', 'path']
def __init__(self, bus, root, path, iface_type):
self.obj = bus.get_object(root, path)
self.iface_type = iface_type
self._iface = None
self._props_iface = None
def __getattr__(self,... |
def distributed_worker(main_func: Callable[(..., _RT)], args: Tuple[(Any, ...)], kwargs: Dict[(str, Any)], backend: str, init_method: Optional[str]=None, dist_params: Optional[DistributedParams]=None, return_save_file: Optional[str]=None, timeout: timedelta=DEFAULT_TIMEOUT, shared_context: Optional[BaseSharedContext]=N... |
def lazy_import():
from fastly.model.logging_common_response import LoggingCommonResponse
from fastly.model.logging_newrelicotlp_additional import LoggingNewrelicotlpAdditional
from fastly.model.service_id_and_version_string import ServiceIdAndVersionString
from fastly.model.timestamps import Timestamps... |
class qos(object):
__qos_queue = None
__qtype = 0
def __init__(self, qtype):
self.__qos_queue = {}
self.__qtype = qtype
def add_to_queue(self, ipdata):
ip_ver = ((ipdata[0] & 240) >> 4)
if (ip_ver == 4):
if (self.__qtype == QTYPE_SRC):
address ... |
class TestSyncSecAggServer():
def test_sync_secagg_server_init(self) -> None:
model = SampleNet(TwoFC())
fixed_point_config = FixedPointConfig(num_bytes=2, scaling_factor=100)
server = instantiate(SyncSecAggServerConfig(fixedpoint=fixed_point_config), global_model=model)
assertEqual(... |
def _add_analysis_filter_to_query(key: str, value: Any, subkey: str):
if hasattr(AnalysisEntry, subkey):
if (subkey == 'summary'):
return _get_array_filter(AnalysisEntry.summary, key, value)
return (getattr(AnalysisEntry, subkey) == value)
return _add_json_filter(key, value, subkey) |
class StartStopExpand(Expand):
def __init__(self, config, **kwargs):
super().__init__(config, **kwargs)
x = self.start
all = []
while (x <= self.end):
all.append(x)
x += self.step
result = [list(g) for (_, g) in itertools.groupby(all, key=self.grouper_... |
def train_model(train_file, eval_file, scale, output_dir):
train_dataset = TrainAugmentDataset(train_file, scale=scale)
val_dataset = EvalDataset(eval_file)
training_args = TrainingArguments(output_dir=output_dir, num_train_epochs=1000)
config = EdsrConfig(scale=scale, n_resblocks=32, n_feats=256)
m... |
def test_window_opacity_set_to_default_on_startup(mult_opacity_server: FlashServer, list_only_test_windows: None, windows: list[Window]) -> None:
with server_running(mult_opacity_server):
assert (windows[0].opacity == pytest.approx(0.2))
assert (windows[1].opacity == pytest.approx(0.5)) |
class SyncHighlighter(YamlHighlighter):
def __init__(self, parent=None):
YamlHighlighter.__init__(self, parent)
tagList = ['\\bignore_hosts\\b', '\\bsync_hosts\\b', '\\bignore_nodes\\b', '\\bsync_nodes\\b', '\\bignore_topics\\b', '\\bignore_publishers\\b', '\\bignore_topics\\b', '\\bsync_topics\\b',... |
class Solution():
def checkInclusion(self, p: str, s: str) -> bool:
from collections import Counter
counter = Counter(p)
start = 0
c2 = {}
for (i, c) in enumerate(s):
if (c not in counter):
start = (i + 1)
c2 = {}
co... |
class RxFrameErr(base_tests.SimpleDataPlane):
def runTest(self):
logging.info('Running Rx_Frame_Err test')
of_ports = config['port_map'].keys()
of_ports.sort()
self.assertTrue((len(of_ports) > 1), 'Not enough ports for test')
delete_all_flows(self.controller)
logging.... |
_dict
def _get_default_genesis_params(genesis_state: AccountState) -> Iterable[Tuple[(str, Union[(BlockNumber, int, None, bytes, Address, Hash32)])]]:
for (key, value) in GENESIS_DEFAULTS:
if ((key == 'state_root') and genesis_state):
pass
else:
(yield (key, value))
(yiel... |
def extractHallucieWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) ... |
def check_errors(thr, shape_and_axes, atol=2e-05, rtol=0.001):
dtype = numpy.complex64
(shape, axes) = shape_and_axes
data = get_test_array(shape, dtype)
fft = FFT(data, axes=axes)
fftc = fft.compile(thr)
data_dev = thr.to_device(data)
fftc(data_dev, data_dev)
fwd_ref = numpy.fft.fftn(da... |
def get_perturbed_head(head):
up_count = 0
while ((get_height(head) > 0) and (random.random() < LATENCY_FACTOR)):
head = blocks[head][1]
up_count += 1
for _ in range(random.randrange((up_count + 1))):
if (head in children):
head = random.choice(children[head])
return ... |
class OptionSeriesPackedbubbleLabel(Options):
def boxesToAvoid(self):
return self._config_get(None)
def boxesToAvoid(self, value: Any):
self._config(value, js_type=False)
def connectorAllowed(self):
return self._config_get(False)
def connectorAllowed(self, flag: bool):
se... |
def test_def_active_live_nok_nok(unused_tcp_port):
custom_range = range(unused_tcp_port, (unused_tcp_port + 1))
(host, port, orig_sock) = port_handler.find_available_port(custom_range=custom_range, custom_host='127.0.0.1')
assert (port == unused_tcp_port)
assert (orig_sock is not None)
assert (orig_... |
def protocol_specific_classes(alice):
if alice.connection.has_protocol(ETHProtocolV63):
return (ETHV63API, ETHV63HandshakeReceipt, StatusV63, StatusV63PayloadFactory)
elif alice.connection.has_protocol(ETHProtocolV64):
return (ETHV64API, ETHHandshakeReceipt, Status, StatusPayloadFactory)
eli... |
class Notifier(QtCore.QObject):
def __init__(self, parent: Optional[QtCore.QObject]) -> None:
super().__init__(parent=parent)
self.com = Communicate(parent=self)
self.com.send_notification.connect(self._send_notification)
def _compose_notification(capture: Capture) -> tuple[(str, str)]:
... |
(nopython=True, cache=const.numba_cache)
def get_u_vec(rvw, phi, R, s):
if (s == const.rolling):
return np.array([1.0, 0.0, 0.0])
rel_vel = rel_velocity(rvw, R)
if (rel_vel == 0.0).all():
return np.array([1.0, 0.0, 0.0])
return ptmath.coordinate_rotation(ptmath.unit_vector(rel_vel), (- p... |
def extractDramanticsBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type)... |
def filter_all_services(wf, query):
services = wf.cached_data('brew_all_services', get_all_services, session=True)
query_filter = query.split()
if (len(query_filter) > 1):
return wf.filter(query_filter[1], services, key=(lambda x: x['name']), match_on=MATCH_SUBSTRING)
return services |
class OptionSeriesOrganizationDatalabelsLinktextpathAttributes(Options):
def startOffset(self):
return self._config_get('95%')
def startOffset(self, num: float):
self._config(num, js_type=False)
def textAnchor(self):
return self._config_get('end')
def textAnchor(self, text: str):... |
class inDB(DBValidator):
def __init__(self, db, tablename, fieldname='id', dbset=None, label_field=None, multiple=False, orderby=None, message=None):
super().__init__(db, tablename, fieldname=fieldname, dbset=dbset, message=message)
self.label_field = label_field
self.multiple = multiple
... |
class TestUniqueValuesShare(BaseFeatureDataQualityMetricsTest):
name: ClassVar = 'Share of Unique Values'
def get_stat(self, current: NumericCharacteristics):
return current.unique_percentage
def get_condition_from_reference(self, reference: Optional[ColumnCharacteristics]) -> TestValueCondition:
... |
class OptionPlotoptionsVariwideStatesInactive(Options):
def animation(self) -> 'OptionPlotoptionsVariwideStatesInactiveAnimation':
return self._config_sub_data('animation', OptionPlotoptionsVariwideStatesInactiveAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, fl... |
def prophet_train(data):
model = Prophet(daily_seasonality=False, yearly_seasonality=False, holidays=holiday_df, holidays_prior_scale=10)
model.add_seasonality(name='weekly', period=7, fourier_order=3, prior_scale=0.1)
model.fit(data)
future = model.make_future_dataframe(periods=7, freq='d')
forecas... |
class TestTrainerParams(unittest.TestCase):
def test_default_trainer_conf(self) -> None:
cs = ConfigStore.instance()
cs.store(name='trainer', node=TrainerConf())
with initialize():
trainer_conf = compose(config_name='trainer')
trainer_params = get_trainer_params(train... |
def generate_docs_only_subset(paths: List[str]) -> Dict[(str, Any)]:
docs_only_subset = {}
for path in paths:
split_path = path.split('.')[::(- 1)]
current_obj = docs_only_subset
while (len(split_path) > 1):
temp_path = split_path.pop()
if (not current_obj.get(tem... |
def alt_bn128_add(evm: Evm) -> None:
data = evm.message.data
charge_gas(evm, Uint(500))
x0_bytes = buffer_read(data, U256(0), U256(32))
x0_value = U256.from_be_bytes(x0_bytes)
y0_bytes = buffer_read(data, U256(32), U256(32))
y0_value = U256.from_be_bytes(y0_bytes)
x1_bytes = buffer_read(data... |
class ProjectMixinTester(unittest.TestCase):
def setUp(self):
super(ProjectMixinTester, self).setUp()
self.test_stat1 = Status(name='On Hold', code='OH')
self.test_stat2 = Status(name='Work In Progress', code='WIP')
self.test_stat3 = Status(name='Approved', code='APP')
self.t... |
class CycleBreakerTransform(StatefulDashTransform):
def __init__(self):
super().__init__()
def transform_layout(self, layout):
children = (_as_list(layout.children) + self.components)
layout.children = children
def apply(self, callbacks, clientside_callbacks):
cycle_inputs = ... |
class MPIFunctionTask(PythonFunctionTask[MPIJob]):
_MPI_JOB_TASK_TYPE = 'mpi'
_MPI_BASE_COMMAND = ['mpirun', '--allow-run-as-root', '-bind-to', 'none', '-map-by', 'slot', '-x', 'LD_LIBRARY_PATH', '-x', 'PATH', '-x', 'NCCL_DEBUG=INFO', '-mca', 'pml', 'ob1', '-mca', 'btl', '^openib']
def __init__(self, task_c... |
class OneOfTests(SignatureFixtures):
_test = _test_annotated_signature
exact = (RepTests.oneof_basic, ('hello',), ['hello'], {})
icase = (RepTests.oneof_basic, ('Hello',), ['hello'], {})
def test_show_list(self):
func = support.f('par:a', globals={'a': RepTests.oneof_help[1]})
(out, err)... |
def filter_extension_controller_fortigate_profile_data(json):
option_list = ['id', 'lan_extension', 'name']
json = remove_invalid_fields(json)
dictionary = {}
for attribute in option_list:
if ((attribute in json) and (json[attribute] is not None)):
dictionary[attribute] = json[attrib... |
def default_text_header(iline, xline, offset):
lines = {1: ('DATE %s' % datetime.date.today().isoformat()), 2: 'AN INCREASE IN AMPLITUDE EQUALS AN INCREASE IN ACOUSTIC IMPEDANCE', 3: 'Written by libsegyio (python)', 11: 'TRACE HEADER POSITION:', 12: (' INLINE BYTES %03d-%03d | OFFSET BYTES %03d-%03d' % (iline, ... |
class WTypeTyper(Typer):
def supported() -> bool:
return (is_wayland() and is_installed('wtype'))
def name() -> str:
return 'wtype'
def get_active_window(self) -> str:
return 'not possible with wtype'
def type_characters(self, characters: str, active_window: str) -> None:
... |
class MongoDBConnector(BaseConnector[MongoClient]):
def build_uri(self) -> str:
config = MongoDBSchema(**(self.configuration.secrets or {}))
user_pass: str = ''
default_auth_db: str = ''
if (config.username and config.password):
user_pass = f'{config.username}:{config.pas... |
class TestChoiceFieldChoicesValidate(TestCase):
CHOICES = [(0, 'Small'), (1, 'Medium'), (2, 'Large')]
SINGLE_CHOICES = [0, 1, 2]
CHOICES_NESTED = [('Category', ((1, 'First'), (2, 'Second'), (3, 'Third'))), (4, 'Fourth')]
MIXED_CHOICES = [('Category', ((1, 'First'), (2, 'Second'))), 3, (4, 'Fourth')]
... |
class OptionSeriesTilemapSonificationContexttracksMappingNoteduration(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
class OptionPlotoptionsDumbbellSonificationTracksMappingPitch(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get('y')
def mapTo(self, text: str):
sel... |
class PPOAgent(Agent):
def __init__(self, model: ModelLike, deterministic_policy: bool=False, replay_buffer: Optional[ReplayBufferLike]=None, controller: Optional[ControllerLike]=None, optimizer: Optional[torch.optim.Optimizer]=None, batch_size: int=512, max_grad_norm: float=1.0, gamma: float=0.99, gae_lambda: floa... |
class ApproxValue(FrozenBaseModel, ExcludeNoneMixin):
class Config():
smart_union = True
DEFAULT_RELATIVE: ClassVar = 1e-06
DEFAULT_ABSOLUTE: ClassVar = 1e-12
value: Numeric
relative: Numeric
absolute: Numeric
def __init__(self, value: Numeric, relative: Optional[Numeric]=None, absol... |
def test_workflow_config_duplicate_log_message(caplog, monkeypatch):
def get_mock_config():
workflow_mock = Mock(spec=workflow_config.WorkflowConfig)
workflow_mock.name = 'same_name'
workflow_mock.config_path = '/duplicate/path'
workflow_mock.function_dir = 'func_dir'
return ... |
class GymDialogues(BaseGymDialogues):
def __init__(self, **kwargs: Any) -> None:
def role_from_first_message(message: Message, receiver_address: Address) -> BaseDialogue.Role:
return GymDialogue.Role.ENVIRONMENT
BaseGymDialogues.__init__(self, self_address=str(PUBLIC_ID), role_from_first... |
class TestUpdateOtherFieldHook(unittest.TestCase):
def test_init_event_update_field_hook(self) -> None:
dummy_obj = DummyInstance('01', '//fbsource')
self.assertEqual(dummy_obj.name, 'Tupper01')
self.assertEqual(dummy_obj.output_path, '//fbsource:output')
self.assertEqual(dummy_obj.s... |
class Solution():
def longestStrChain(self, words: List[str]) -> int:
def fill_pre(w2, ss, dd):
if (w2 not in ss):
return 0
if (w2 in dd):
return dd[w2]
m = 1
for i in range(len(w2)):
w = (w2[:i] + w2[(i + 1):])
... |
def socket_reader(sockobj, outq, exit_event):
while (not exit_event.is_set()):
try:
buf = sockobj.recv(1)
if (len(buf) < 1):
break
outq.put(buf)
except socket.timeout:
continue
except OSError:
break |
def test_dispatch_to_response_pure_invalid_result() -> None:
def not_a_result() -> None:
return None
assert (dispatch_to_response_pure(deserializer=default_deserializer, validator=default_validator, post_process=identity, context=NOCONTEXT, methods={'not_a_result': not_a_result}, request='{"jsonrpc": "2... |
class OgfOcf():
def __init__(self, name, ogf=b'\x00', ocf=b'\x00'):
self.name = name
self.ogf = ogf
self.ocf = ocf
def encode(self):
val = pack('<H', ((ord(self.ogf) << 10) | ord(self.ocf)))
return val
def decode(self, data):
val = unpack('<H', data[:len(self)... |
def test_string_counter():
counter = StringCounter()
counter2 = StringCounter()
counter.add(None)
counter2.add(None)
assert (str(counter) == '')
counter.add('foo')
counter.add('bar')
counter.add('foo')
counter2.add('baz')
assert (str(counter) == 'foo=2, bar=1')
assert (str(co... |
_os(*metadata.platforms)
def main():
mstsc = 'C:\\Users\\Public\\mstsc.exe'
path = 'C:\\Users\\Public\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup'
argpath = "C:\\Users\\Public\\AppData\\Roaming\\Microsoft\\Windows\\'Start Menu'\\Programs\\Startup"
common.copy_file(EXE_FILE, msts... |
def test_snr():
measurements = np.array([[[1, 2, 3], [4, 5, 6]], [[2, 3, 4], [5, 6, 7]]])
snr = calc_signal_to_noise_ratio(measurements)
snr_with_flat = calc_signal_to_noise_ratio(measurements.reshape((2, (- 1))))
correct_snr = np.array([3, 5, 7, 9, 11, 13])
assert_array_equal(snr, correct_snr)
... |
class Main():
_main = None
def __init__(self, exaile):
from xlgui import icons, main, panels, tray, progress
Gdk.set_program_class('Exaile')
GLib.set_application_name('Exaile')
os.environ['PULSE_PROP_media.role'] = 'music'
self.exaile = exaile
self.first_removed =... |
class Test_icmpv6_router_advert(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_default_args(self):
prev = ipv6(nxt=inet.IPPROTO_ICMPV6)
ic = icmpv6.icmpv6(type_=icmpv6.ND_ROUTER_ADVERT, data=icmpv6.nd_router_advert())
prev.serialize(ic, No... |
def test_init_receives_args_and_kwargs(SMTestBase):
class StateMachine(SMTestBase):
def __init__(self, foo, bar=42, baz=31337):
assert (foo == 11)
assert (bar in (32, 42))
assert (baz in (69, 31337))
state_machine(StateMachine, 11, baz=69, settings={'max_examples': 2}... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.