code
stringlengths
281
23.7M
class TestScaffoldHandler(): def setup_class(cls): cls.handler = MyScaffoldHandler('handler', SkillContext()) def test_supported_protocol(self): assert (self.handler.SUPPORTED_PROTOCOL is None) def test_setup(self): with pytest.raises(NotImplementedError): self.handler.se...
class OptionSeriesSankeySonificationTracksMappingTremoloSpeed(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): se...
class FormatInline(admin.GenericTabularInline): model = Format fields = ('format', 'progress', 'file', 'width', 'height', 'duration') readonly_fields = fields extra = 0 max_num = 0 def has_add_permission(self, *args, **kwargs): return False def has_delete_permission(self, *args, **kw...
def test_pct_to_log_return(): np.random.seed(7) tests = pd.Series([(1 + np.random.rand()) for _ in range(100)]) pct_rtns = tests.pct_change().fillna(0) log_rtns = perf.pct_to_log_return(pct_rtns) recon1 = (1 + pct_rtns).cumprod() recon2 = np.exp(log_rtns.cumsum()) assert np.allclose(recon1, ...
def forward(model: Model[(SeqT, SeqT)], Xseq: SeqT, is_train: bool) -> Tuple[(SeqT, Callable)]: layer: Model[(Padded, Padded)] = model.layers[0] if isinstance(Xseq, Padded): return cast(Tuple[(SeqT, Callable)], layer(Xseq, is_train)) elif isinstance(Xseq, Ragged): return cast(Tuple[(SeqT, Ca...
def test_assigning_old_form_name(db): event = EventFactoryBasic() speaker_custom_form = CustomForms(event=event, field_identifier='speakingExperience', form='speaker', type='text') attendee_custom_form = CustomForms(event=event, field_identifier='taxBusinessInfo', form='attendee', type='text') session_c...
class Extension(extensions.Extension): ident = 'navigationgroups' groups = [('default', _('Default')), ('footer', _('Footer'))] def handle_model(self): self.model.add_to_class('navigation_group', models.CharField(_('navigation group'), choices=self.groups, default=self.groups[0][0], max_length=20, b...
def test_insert_intersecting_cases_anywhere(task): condition_handler = ConditionHandler() cond_2_symbol = condition_handler.add_condition(Condition(OperationType.equal, [var_c, const[2]])) ast = AbstractSyntaxForest(condition_handler=condition_handler) root = ast.factory.create_seq_node() missing_ca...
class NibeClimateRoom(NibeClimate): def __init__(self, system: NibeSystem, climate: ClimateSystem): parameters = {climate.room_temp, climate.room_setpoint_heat, climate.room_setpoint_cool} super().__init__(system, climate, parameters) self.entity_id = ENTITY_ID_FORMAT.format(f'{DOMAIN_NIBE}_...
class PostgresElasticsearchIndexerController(AbstractElasticsearchIndexerController): def ensure_view_exists(self, sql_view_name: str, force_recreate=True) -> None: ensure_view_exists(view_name=sql_view_name, force=force_recreate) def _count_of_records_to_process(self, config) -> Tuple[(int, int, int)]:...
class Timer(): _formats = ('{:,} d', '{} h', '{} m', '{} s', '{} ms') def __init__(self, message=None, success_logger=print, failure_logger=print): self.message = message self.success_logger = success_logger self.failure_logger = failure_logger self.start() def __enter__(self...
def to_unit(seconds, unit, model): if (not unit): return None lut = {'min': 60, 'h': 3600, 'd': 86400, 'w': 604800, 'm': 2419200, 'y': } if (model in ['effort', 'length']): from stalker import defaults day_wt = (defaults.daily_working_hours * 3600) week_wt = (defaults.weekly_...
def test_with_debug(): on_init = MagicMock() on_forward = MagicMock() on_backprop = MagicMock() model = with_debug(Linear(), on_init=on_init, on_forward=on_forward, on_backprop=on_backprop) on_init.assert_not_called() on_forward.assert_not_called() on_backprop.assert_not_called() X = mod...
def event_model_to_event(event_model): event = Event(key=event_model.key, value=event_model.value) event.namespace = event_model.namespace event.sender = event_model.sender event.offset = event_model.offset event.create_time = event_model.create_time event.context = event_model.context retur...
def _ask_about_patch(patch, editor, default_no): global yes_to_all default_action = ('n' if default_no else 'y') terminal.terminal_clear() terminal.terminal_print(('%s\n' % patch.render_range()), color='WHITE') print() lines = list(open(patch.path)) size = list(terminal.terminal_get_size()) ...
class TestSolidLibrary(unittest.TestCase): def test_solid_library(self): sample_name = 'PJB_pool' library_name = 'PJB_NY17' sample = SolidSample(sample_name) library = SolidLibrary(library_name, sample) self.assertEqual(library_name, library.name) self.assertEqual('PJ...
def get_public_ids_to_update() -> Set[PackageId]: result: Set[PackageId] = set() last = get_hashes_from_last_release() now = get_hashes_from_current_release() last_by_type = split_hashes_by_type(last) now_by_type = split_hashes_by_type(now) for type_ in TYPES: for (key, value) in last_by...
def _fill_dtype_registry(respect_windows=True): import sys import platform _register_dtype(bool, 'bool') _register_dtype(numpy.bool_, 'bool') _register_dtype(numpy.int8, 'char') _register_dtype(numpy.uint8, 'unsigned char') _register_dtype(numpy.int16, 'short') _register_dtype(numpy.uint...
def click_validate_enum(enumClass, ctx, param, value): if (value is not None): try: enumClass[value] except KeyError: allowed = map(attrgetter('name'), enumClass) raise click.BadParameter('allowed values: {}'.format(', '.join(allowed))) return value
class OptionPlotoptionsWordcloudSonificationDefaultspeechoptionsMappingTime(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: st...
class OptionSeriesDependencywheelSonificationContexttracksMappingPlaydelay(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 generate_json_for_fogbench(asset_name): subprocess.run(['cd $FLEDGE_ROOT/data && mkdir -p tests'], shell=True, check=True) fogbench_template_path = os.path.join(os.path.expandvars('${FLEDGE_ROOT}'), 'data/tests/{}'.format(TEMPLATE_NAME)) with open(fogbench_template_path, 'w') as f: f.write(('[{"...
class OptionPlotoptionsTilemapSonificationDefaultinstrumentoptions(Options): def activeWhen(self) -> 'OptionPlotoptionsTilemapSonificationDefaultinstrumentoptionsActivewhen': return self._config_sub_data('activeWhen', OptionPlotoptionsTilemapSonificationDefaultinstrumentoptionsActivewhen) def instrument...
def inprocess(model_name, use_existing_configuration=False, **kwargs): from .lmtp_dcmodel import lmtp_model assert (not model_name.startswith('openai/')), 'openai/ models cannot be loaded with inprocess=True, they always use the remote API.' kwargs = rename_model_args(kwargs) if model_name.startswith('l...
class Strategy(Model): def __init__(self, **kwargs: Any) -> None: self._admin_host = kwargs.pop('admin_host', DEFAULT_ADMIN_HOST) self._admin_port = kwargs.pop('admin_port', DEFAULT_ADMIN_PORT) self._ledger_url = kwargs.pop('ledger_url', DEFAULT_LEDGER_URL) self._seed = (kwargs.pop('...
def install_plugin(_type, plugin, branch='develop', plugin_lang='python', use_pip_cache=True): if (plugin_lang == 'python'): path = '$FLEDGE_ROOT/tests/system/python/scripts/install_python_plugin {} {} {} {}'.format(branch, _type, plugin, use_pip_cache) else: path = '$FLEDGE_ROOT/tests/system/py...
def test_beaconmetadata_set_membership(): metadata_set = set() m1 = BeaconMetadata(magic=48879, pid=74565, info=b'testing') m2 = BeaconMetadata(magic=48879, pid=74565, info=b'testing') m3 = BeaconMetadata(magic=48879, pid=74565, info=b'12345') metadata_set.add(m1) assert (list(m1._values.items()...
() def setup_to_pass(): rules = ['-w /etc/group -p wa -k identity', '-w /etc/passwd -p wa -k identity', '-w /etc/gshadow -p wa -k identity', '-w /etc/shadow -p wa -k identity', '-w /etc/security/opasswd -p wa -k identity'] for rule in rules: print(shellexec(f'echo "{rule}" >> /etc/audit/rules.d/pytest.r...
def get_latest_version_available_in_registry(ctx: Context, item_type: str, item_public_id: PublicId, aea_version: Optional[str]=None) -> PublicId: is_local = ctx.config.get('is_local') is_mixed = ctx.config.get('is_mixed') try: if is_mixed: latest_item_public_id = get_latest_public_id_mi...
class RequestFormatter(logging.Formatter): def format(self, record): s = logging.Formatter.format(self, record) try: return (('[%s] [%s] [%s %s] ' % (self.formatTime(record), request.remote_addr, request.method, request.path)) + s) except: return (('[%s] [SYS] ' % sel...
class HelpIntentHandler(AbstractRequestHandler): def can_handle(self, handler_input): return ask_utils.is_intent_name('AMAZON.HelpIntent')(handler_input) def handle(self, handler_input): speak_output = "You can ask me to do just about anything, and I'll send it to Fixie." return handler_...
def vm_fixture_mark_fn(fixture_path, fixture_name): if fixture_path.startswith('vmPerformance'): return pytest.mark.skip('Performance tests are really slow') elif (fixture_path == 'vmSystemOperations/createNameRegistrator.json'): return pytest.mark.skip('Skipped in go-ethereum due to failure wit...
def set_capacities_constant(topology, capacity, capacity_unit='Mbps', links=None): if (capacity <= 0): raise ValueError('Capacity must be positive') if (not (capacity_unit in capacity_units)): raise ValueError('The capacity_unit argument is not valid') conversion_factor = 1 if (('capacit...
class EventForm(ModelForm): class Meta(): model = Event fields = ('name', 'event_slug', 'limit_proposal_date', 'registration_closed', 'email', 'place', 'external_url', 'abstract', 'event_information', 'use_installations', 'use_installers', 'is_flisol', 'use_talks', 'use_collaborators', 'use_proposal...
class DomainResponse(ModelComposed): allowed_values = {} validations = {} _property def additional_properties_type(): lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(): lazy_import() ...
class DistributedShampooGraftingTest(unittest.TestCase): def _construct_quadratic(self, device: torch.device) -> Tuple[(nn.Module, nn.Module, torch.Tensor, torch.Tensor)]: data = torch.arange(10, dtype=torch.float, device=device) model = nn.Sequential(nn.Linear(10, 1, bias=False)).to(device=device) ...
def test_chain_vector(): coords = grid_coordinates(((- 10), 0, 0, 10), spacing=0.1) coefs = [(- 50), (- 0.5), 2.1] trend = ((coefs[0] + (coefs[1] * coords[0])) + (coefs[2] * coords[1])) data = (trend, trend.copy()) chain = Chain([('mean', BlockReduce(np.mean, spacing=0.5)), ('trend', Vector([Trend(d...
def gen_int_var(values: List[int], name: str=None, symbolic_value: Optional[sympy.Basic]=None): from aitemplate.compiler.base import IntImm, IntVar values = list(set(values)) if (len(values) == 1): return IntImm(values[0], name=name) elif (len(values) > 1): return IntVar(values, name=nam...
class FaucetCoprocessorTest(FaucetUntaggedTest): N_UNTAGGED = 3 N_TAGGED = 1 CONFIG = '\n interfaces:\n %(port_1)d:\n coprocessor: {strategy: vlan_vid}\n mirror: %(port_4)d\n %(port_2)d:\n native_vlan: 100\n %(port_3)d:\n ...
def test_gpg_list_all_keyids(common): import_key('gpgsync_test_pubkey.asc', common.gpg.homedir) key1_fp = common.clean_fp(b'3B72C32B49CBB5BBDD57440E1D07D43448FB8382') import_key('pgpsync_multiple_uids.asc', common.gpg.homedir) key2_fp = common.clean_fp(b'D86B4D4BB5DFDD378B58D4D3F121AC6230396C33') as...
def test_generate_ass_repr_for_building_layout_without_creating_building_look_dev_first(create_test_data, store_local_session, create_pymel, create_maya_env): data = create_test_data gen = RepresentationGenerator(version=data['building1_layout_main_v003']) with pytest.raises(RuntimeError) as cm: gen...
class ImportExportCaseSQLLite_File(ImportExportTestCase, BenjiTestCaseBase, TestCase): VERSIONS = 3 CONFIG = "\n configurationVersion: '1'\n processName: benji\n logFile: /dev/stderr\n blockSize: 4096\n defaultStorage: file\n storages:\n ...
def is_iso_datetime(string): try: datetime.datetime.strptime(string, DATE_TIME_PATTERN) return True except ValueError: pass try: datetime.datetime.strptime(string, '%Y-%m-%dT%H:%M:%S.%fZ') return True except ValueError: pass return False
class TestMultipleChoiceField(FieldValues): valid_inputs = {(): set(), ('aircon',): {'aircon'}, ('aircon', 'manual'): {'aircon', 'manual'}} invalid_inputs = {'abc': ['Expected a list of items but got type "str".'], ('aircon', 'incorrect'): ['"incorrect" is not a valid choice.']} outputs = [(['aircon', 'manu...
def init_crop_config(rows: List[dict]): for item in rows: crop_class: Crop = farming_table.get(item['template_id'], None) if crop_class: crop_class.name = item['name'] crop_class.charge_time = timedelta(seconds=item['charge_time']) crop_class.energy_consumed = ite...
def extractAngeloflight360HomeBlog(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_typ...
.parametrize('duration, recognized, subject, text', [pytest.param(30, ['', ' ', '', ' '], 'Voice: ...', ' ', id='short_recognized'), pytest.param(30, [], 'Voice note to self', ' ', id='short_unrecognized'), pytest.param(90, [], 'Voice note to self', ' ', id='long')]) def test_send_voice(bot_app, update, send_mail...
def test_read_configuration_from_pyproject_toml_file_not_found(caplog: LogCaptureFixture) -> None: pyproject_toml_path = Path('a_non_existent_pyproject.toml') with caplog.at_level(logging.DEBUG): assert (read_configuration_from_pyproject_toml(click.Context(click.Command('')), click.UNPROCESSED(None), py...
.skip_ci ('xtb') .parametrize('opt_cls, _opt_kwargs, ref_cycle', [(BFGS, {'update': 'bfgs'}, 25), (LBFGS, {'keep_last': 25, 'double_damp': False, 'gamma_mult': False}, 25), (BFGS, {'update': 'damped'}, 25), (BFGS, {'update': 'double'}, 16), (LBFGS, {'keep_last': 10, 'double_damp': True, 'gamma_mult': True, 'align': Fal...
('keyring.set_password') def test_keyring_store_set(kr_set_password: MagicMock): kr_set_password.return_value = None assert KeyringStore.store(Credentials(access_token='a', refresh_token='r', for_endpoint='f')) kr_set_password.side_effect = NoKeyringError() assert (KeyringStore.retrieve('example2.com') ...
class ExaileParser(spydaap.parser.Parser): _string_map = {'title': 'dmap.itemname', 'artist': 'daap.songartist', 'composer': 'daap.songcomposer', 'genre': 'daap.songgenre', 'album': 'daap.songalbum'} _int_map = {'bpm': 'daap.songbeatsperminute', 'year': 'daap.songyear', 'tracknumber': 'daap.songtracknumber', 't...
def test_fail(testdir): testdir.makepyfile("\n import unittest\n\n\n class TestCase(unittest.TestCase):\n def test_fail(self):\n self.assertTrue(str(True) == 'Garble')\n ") result = testdir.runpytest('-v') result.stdout.fnmatch_lines(['*::TestCase::test_fail ... FA...
_type(ofproto.OFPPDPT_RECIRCULATE) class OFPPortDescPropRecirculate(OFPPortDescProp): _PORT_NO_PACK_STR = '!I' def __init__(self, type_=None, length=None, port_nos=None): port_nos = (port_nos if port_nos else []) super(OFPPortDescPropRecirculate, self).__init__(type_, length) self.port_n...
def test_categorical_sample(): logits = torch.from_numpy(np.random.randn(5)) dist = CategoricalProbabilityDistribution(logits=logits, action_space=spaces.Discrete(5), temperature=1.0) assert (dist.sample().numpy().ndim == 0) assert (dist.deterministic_sample().numpy().ndim == 0) logits = torch.from_...
def test_app_client_async(test_app: str): request_handle = apps.submit(test_app, arguments={'lhs': 1, 'rhs': 2}) assert (request_handle.get() == {'result': 3}) request_handle = apps.submit(test_app, arguments={'lhs': 2, 'rhs': 3, 'wait_time': 5}) for event in request_handle.iter_events(logs=True): ...
def check_app_installed(app, bench_path='.'): try: out = subprocess.check_output(['bench', '--site', 'all', 'list-apps', '--format', 'json'], stderr=open(os.devnull, 'wb'), cwd=bench_path).decode('utf-8') except subprocess.CalledProcessError: return None try: apps_sites_dict = json.l...
.parametrize('test_input, expected', [(1, TypeError), (1.0, TypeError), ('invalid choice', SystemExit), (['all', '-i'], SystemExit), (['all', '--invalid'], SystemExit)]) def test_tools_parsers_raises(test_input, expected): for parser in [tools_install_parser, tools_uninstall_parser, tools_reinstall_parser]: ...
def validate_updated_instances_removals(updated_dataset_config: DatasetConfig, original_template_config: Dict, original_template_dataset: Dict, key: str, fides_key: str): assert (len(updated_dataset_config.ctl_dataset.collections) == (len(original_template_dataset['collections']) - 1)) updated_saas_config = upd...
def make_v1(apps, packages, repodir, repodict, requestsdict, fdroid_signing_key_fingerprints): def _index_encoder_default(obj): if isinstance(obj, set): return sorted(list(obj)) if isinstance(obj, datetime): return int((calendar.timegm(obj.timetuple()) * 1000)) if isi...
def lazy_import(): from fastly.model.dictionary_item import DictionaryItem from fastly.model.dictionary_item_response_all_of import DictionaryItemResponseAllOf from fastly.model.timestamps import Timestamps globals()['DictionaryItem'] = DictionaryItem globals()['DictionaryItemResponseAllOf'] = Dicti...
.usefixtures('use_tmpdir') def test_running_flow_given_env_variables_with_same_name_as_parent_env_variables_will_overwrite(monkeypatch): version = '1111.11' with open('flow', 'w', encoding='utf-8') as filehandle: filehandle.write('#!/bin/sh\n') filehandle.write('echo $ENV1 > out.txt\n') ...
class User(Base): __tablename__ = 'users' __exclude_columns__ = ('comments', 'updates', 'buildroot_overrides') __include_extras__ = ('avatar', 'openid') __get_by__ = ('name',) name = Column(Unicode(64), unique=True, nullable=False) email = Column(UnicodeText) comments = relationship('Comment...
def build_bnf_codes_query(base_query, filter_): if (base_query is None): base_query = 'SELECT bnf_code FROM {hscic}.presentation' if (filter_ is None): query = base_query else: where_clause = build_bnf_codes_query_where(filter_) query = '\n WITH subquery AS ({})\n ...
class CloudSqlRuleBook(bre.BaseRuleBook): def __init__(self, rule_defs=None): super(CloudSqlRuleBook, self).__init__() self.resource_rules_map = {} if (not rule_defs): self.rule_defs = {} else: self.rule_defs = rule_defs self.add_rules(rule_defs) ...
def _create_plot_component(): npts = 2000 x = sort(random(npts)) y = random(npts) pd = ArrayPlotData() pd.set_data('index', x) pd.set_data('value', y) plot = Plot(pd) plot.plot(('index', 'value'), type='scatter', name='my_plot', marker='circle', index_sort='ascending', color='red', marke...
def analyze(to_process: FeatureToProcess, feature_dict: dict): compare_dict = feature_dict.get('compare') feature_dict['stats'] = dict() if compare_dict: compare_dict['stats'] = dict() do_detail_text(to_process, feature_dict) if to_process.is_target(): raise ValueError else: ...
class LogSinkRulesEngineTest(ForsetiTestCase): def setUp(self): self.lsre = lsre self.lsre.LOGGER = mock.MagicMock() self.org_234 = Organization('234', display_name='Organization 234', full_name='organization/234/', data='fake_org_data_234') self.billing_acct_abcd = BillingAccount('A...
def get_responses(): request = {} responses = [] for entry_point in pkg_resources.iter_entry_points(ENTRY_POINT_GROUP): try: loader = entry_point.load() except ImportError: logger.exception('Failed to load entry point %r', entry_point) continue try...
class OptionSeriesPolygonTooltip(Options): def clusterFormat(self): return self._config_get('Clustered points: {point.clusterPointsAmount}') def clusterFormat(self, text: str): self._config(text, js_type=False) def dateTimeLabelFormats(self) -> 'OptionSeriesPolygonTooltipDatetimelabelformats...
class Solution(): def longestIncreasingPath(self, matrix: List[List[int]]) -> int: def find_neighbors(matrix, y, x): curr = matrix[y][x] deltas = [((- 1), 0), (0, (- 1)), (0, 1), (1, 0)] for (yd, xd) in deltas: (yn, xn) = ((y + yd), (x + xd)) ...
class SnmprecGrammar(AbstractGrammar): ALNUMS = set(octs2ints(str2octs((ascii_letters + digits)))) TAG_MAP = {} SNMP_TYPES = (rfc1902.Gauge32, rfc1902.Integer32, rfc1902.IpAddress, univ.Null, univ.ObjectIdentifier, rfc1902.OctetString, rfc1902.TimeTicks, rfc1902.Opaque, rfc1902.Counter32, rfc1902.Counter64,...
class CheckCompiling(): def __init__(self, ts, func): self.has_been_replaced = False self.ts = ts self.func = func def __call__(self, *args, **kwargs): if self.has_been_replaced: return self.func(*args, **kwargs) ts = self.ts if (ts.is_compiling and (n...
class TestSeq2PatBatch(unittest.TestCase): TEST_DIR = os.path.dirname(os.path.abspath(__file__)) DATA_DIR = (((TEST_DIR + os.sep) + 'data') + os.sep) def test_list_to_counter(self): patterns = [[11, 12, 1], [11, 12, 13, 1], [11, 13, 1], [12, 13, 1]] counter = list_to_counter(patterns) ...
(base=RequestContextTask, name='expire.initializing.tickets') def expire_initializing_tickets(): order_expiry_time = get_settings()['order_expiry_time'] query = db.session.query(Order.id).filter((Order.status == 'initializing'), (Order.paid_via == None), ((Order.created_at + datetime.timedelta(minutes=order_exp...
def test_stacktrace_filtered_for_elasticapm(client, django_elasticapm_client): with override_settings(**middleware_setting(django.VERSION, ['elasticapm.contrib.django.middleware.TracingMiddleware'])): resp = client.get(reverse('render-heavy-template')) assert (resp.status_code == 200) transactions =...
def param_cname(param, qualified=False): name = ('_leaf_' + param.name) if qualified: ctype = param.annotation.type.ctype if param.annotation.array: qualifier = ('CONSTANT_MEM' if param.annotation.constant else 'GLOBAL_MEM') return ((((qualifier + ' ') + str(ctype)) + ' *...
class FileWrapper(): def __init__(self, file_path, file_url, file_info) -> None: self.file_path = file_path self.file_url = file_url self.file_info = file_info file_path: Optional[str] file_url: Optional[str] file_info: FileInfo def get_file_content(self): if self.fil...
class PriceListTestCase(unittest.TestCase): def setUp(self): super(PriceListTestCase, self).setUp() self.kwargs = {'name': 'Test Price List'} def test_goods_argument_is_skipped(self): p = PriceList(**self.kwargs) assert (p.goods == []) def test_goods_argument_is_None(self): ...
class _coconut_base_callable(_coconut_baseclass): __slots__ = () def __get__(self, obj, objtype=None): if (obj is None): return self if (_coconut_sys.version_info < (3,)): return _coconut.types.MethodType(self, obj, objtype) else: return _coconut.types...
class Constant(Node): __slots__ = ('type', 'value', 'coord', '__weakref__') def __init__(self, type, value, coord=None): self.type = type self.value = value self.coord = coord def children(self): nodelist = [] return tuple(nodelist) attr_names = ('type', 'value')
class Backbone(nn.Module): def __init__(self, stages_repeats=[4, 8, 4], stages_out_channels=[24, 64, 128, 192, 256], num_classes=1000, inverted_residual=InvertedResidual) -> None: super(Backbone, self).__init__() if (len(stages_repeats) != 3): raise ValueError('expected stages_repeats as...
class ClientMetadata(Record, serializer='json', include_metadata=False, namespace=''): assignment: ClientAssignment url: str changelog_distribution: HostToPartitionMap external_topic_distribution: HostToPartitionMap = cast(HostToPartitionMap, {}) topic_groups: Mapping[(str, int)] = cast(Mapping[(str...
def test_installs_inside_venv(): commands = 'cp -a /rally_ro /rally &&python3 -mvenv .venv &&source .venv/bin/activate &&cd /rally &&python3 -m pip install --upgrade pip &&python3 -m pip install -e . &&esrally list tracks' assert (it.command_in_docker(commands, python_version=MIN_PY_VER) == 0)
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 gen_function(func_attrs: Dict[(str, Any)], template_path: str, header_files: str, backend_spec) -> str: func_name = func_attrs['name'] x = func_attrs['inputs'][0] xdtype = x._attrs['dtype'] exec_paths = EXEC_TEMPLATE.render(indent=' ', dtype=backend_spec.dtype_to_backend_type(xdtype)) return SR...
('tomate.ui.preference', scope=SingletonScope) class PreferenceDialog(Gtk.Dialog): (timer_tab='tomate.ui.preference.timer', extension_tab='tomate.ui.preference.extension') def __init__(self, timer_tab, extension_tab): stack = Gtk.Stack() stack.add_titled(timer_tab.widget, 'timer', _('Timer')) ...
def step3(): from tensorflow.keras.applications.vgg16 import VGG16 from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.vgg16 import decode_predictions, preprocess_input from tensorflow.keras.models import Model from tensorflow.compiler import xla import numpy as n...
class BatchItemResponse(FromJsonMixin): qbo_object_name = 'BatchItemResponse' def __init__(self): super(BatchItemResponse, self).__init__() self.bId = '' self.list_dict = {} self.class_dict = {'Fault': Fault} self._original_object = None self.Fault = None def ...
class TestActionOpen(TestCase): VERSION = {'version': {'number': '8.0.0'}} def builder(self): self.client = Mock() self.client.info.return_value = self.VERSION self.client.cat.indices.return_value = testvars.state_four self.client.indices.get_settings.return_value = testvars.sett...
.parametrize('uri,message', (('/:hi', MALFORMED_URI), ('wrongscheme://public_key:[::]:30303', MALFORMED_URI), ('enode://public_key:[::]:30303', MALFORMED_URI), ('enode://', 'public key must be a 128-character hex string'), ('enode://[::]:30303', 'public key must be a 128-character hex string'), (f'enode://{GOOD_KEY}:30...
def set_env() -> None: os.environ['RANK'] = os.environ.get('RANK', '0') os.environ['WORLD_SIZE'] = os.environ.get('WORLD_SIZE', '1') os.environ['MASTER_PORT'] = os.environ.get('MASTER_PORT', '29830') os.environ['MASTER_ADDR'] = os.environ.get('MASTER_ADDR', 'localhost') os.environ['LOCAL_RANK'] = os...
class TestFipaHandler(ERC1155DeployTestCase): def test_setup(self): assert (self.fipa_handler.setup() is None) self.assert_quantity_in_outbox(0) def test_handle_unidentified_dialogue(self): incorrect_dialogue_reference = ('', '') incoming_message = cast(FipaMessage, self.build_in...
def build_envoy_docker_image(manager: source_manager.SourceManager, commit_hash: str) -> None: builder = envoy_builder.EnvoyBuilder(manager) source_repo = manager.get_source_repository(proto_source.SourceRepository.SRCID_ENVOY) source_repo.commit_hash = commit_hash builder.build_envoy_image_from_source(...
def mock_ert(monkeypatch): ert_mock = MagicMock() ert_mock.forward_model_job_name_list.return_value = ['forward_model_1', 'forward_model_2'] gen_kw = GenKwConfig(name='KEY', forward_init=False, template_file='', transfer_function_definitions=['KEY1 UNIFORM 0 1', 'KEY2 NORMAL 0 1', 'KEY3 LOGNORMAL 0 1'], out...
class Command(BaseCommand): parser = BaseCommand.load_parser(description='SWAT credentials management.') subparsers = parser.add_subparsers(dest='subcommand', title='subcommands', required=True) parser_add = subparsers.add_parser('add', description='Add credentials to the cred store', help='Add credentials ...
def test_ndgrid_2d_antiderivative(ndgrid_2d_data): xy = ndgrid_2d_data.xy z = ndgrid_2d_data.z zi_ad1_expected = ndgrid_2d_data.zi_ad1 spline = csaps.NdGridCubicSmoothingSpline(xy, z, smooth=None).spline spline_ad1: csaps.NdGridSplinePPForm = spline.antiderivative(nu=(1, 1)) zi_ad1 = spline_ad1(...
('flytekit.configuration.plugin.FlyteRemote', spec=FlyteRemote) ('flytekit.clients.friendly.SynchronousFlyteClient', spec=SynchronousFlyteClient) def test_register_sql_task(mock_client, mock_remote): mock_remote._client = mock_client mock_remote.return_value._version_from_hash.return_value = 'dummy_version_from...
def run(proj_dir): exe = exe_name() proj_name = util.get_project_name_from_dir(proj_dir) try: subprocess.call('{} .vscode/{}.code-workspace'.format(exe, proj_name), cwd=proj_dir, shell=True) except OSError: log.error("Failed to run Visual Studio Code as '{}'".format(exe))
class MulticastServer(ControlMixin, ThreadingUDPServer): allow_reuse_address = True def __init__(self, addr, handler, chromecast_addr, poll_interval=0.5, bind_and_activate=True, interfaces=None): ThreadingUDPServer.__init__(self, ('', addr[1]), handler, bind_and_activate) ControlMixin.__init__(s...
def generate_html_detail_text(feature_dict: dict, compare_dict: dict, dataframe_report): template = jinja2_env.get_template('feature_detail_text.html') cols = dict() cur_x = config['Layout'].getint('pair_spacing') padding = config['Layout'].getint('col_spacing') if (compare_dict is not None): ...