code
stringlengths
281
23.7M
class StakingRestClient(Staking): API_URL = '/cosmos/staking/v1beta1' def __init__(self, rest_api: RestClient) -> None: self._rest_api = rest_api def Validators(self, request: QueryValidatorsRequest) -> QueryValidatorsResponse: json_response = self._rest_api.get(f'{self.API_URL}/validators',...
def test_fill_config_overrides(): config = {'cfg': {'one': 1, 'two': {'three': {'': 'catsie.v1', 'evil': True, 'cute': False}}}} overrides = {'cfg.two.three.evil': False} result = my_registry.fill(config, overrides=overrides, validate=True) assert (result['cfg']['two']['three']['evil'] is False) ove...
def parse_css(cspace: 'Space', string: str, start: int=0, fullmatch: bool=True, color: bool=False) -> Optional[Tuple[(Tuple[(Vector, float)], int)]]: target = cspace.SERIALIZE if (not target): target = (cspace.NAME,) tokens = tokenize_css(string, start=start) if (not tokens): return None...
def test_revert_clears_reverted_journal_entries(journal_db): journal_db.set(b'1', b'test-a') assert (journal_db.get(b'1') == b'test-a') checkpoint_a = journal_db.record() journal_db.set(b'1', b'test-b') journal_db.delete(b'1') journal_db.set(b'1', b'test-c') assert (journal_db.get(b'1') == b...
def query_to_parameters(endpoint_method): params_to_not_look_for = {'self', 'args', 'kwargs'} (endpoint_method) def convert_query_parameters_of_endpoint_method(self, *args, **kwargs): kwargs = _convert_query_params(endpoint_method, params_to_not_look_for, **kwargs) return endpoint_method(sel...
def init_wordmap(): wordmap = {'upos': None, 'lemma': None, 'homonym': 0, 'new_para': None, 'kotus_tn': None, 'kotus_av': None, 'plurale_tantum': None, 'possessive': None, 'clitics': None, 'is_proper': None, 'proper_noun_class': None, 'style': None, 'stub': None, 'gradestem': None, 'twolstem': None, 'grade_dir': No...
class slice_reshape_scatter(Operator): def is_valid(cat_op: Operator, reshape_op: Operator, cat_op_2: Operator) -> bool: assert (cat_op._attrs['op'] == 'concatenate') assert (reshape_op._attrs['op'] == 'reshape') assert cat_op_2._attrs['op'].startswith('concatenate') cat_dim = cat_op...
class MeArticleListView(viewsets.ReadOnlyModelViewSet): queryset = Article.objects.filter(is_show=True).order_by('-add_time') serializer_class = ArticleSerializer pagination_class = StandardResultsSetPagination filter_backends = (DjangoFilterBackend,) filter_class = ArticleFilter permission_clas...
class ServeRequest(BaseModel): class Config(): title = f'ServeRequest for {SERVE_APP_NAME_HUMP}' chat_scene: Optional[str] = Field(None, description='The chat scene, e.g. chat_with_db_execute, chat_excel, chat_with_db_qa.', examples=['chat_with_db_execute', 'chat_excel', 'chat_with_db_qa']) sub_chat...
_decorator(removed, name='list') class SubmissionAttributesViewSet(FilterQuerysetMixin, CachedDetailViewSet): serializer_class = SubmissionAttributesSerializer def get_queryset(self): queryset = SubmissionAttributes.objects.all() queryset = self.serializer_class.setup_eager_loading(queryset) ...
def show_in_file_explorer(path: str) -> bool: if (sys.platform == 'win32'): args = [] if (not os.path.isdir(path)): args.append('/select,') args.append(QDir.toNativeSeparators(path)) QProcess.startDetached('explorer', args) elif (sys.platform == 'darwin'): arg...
class Solution(): def minStoneSum(self, piles: List[int], k: int) -> int: ps = [(- a) for a in piles] heapq.heapify(ps) while (k > 0): curr = (- heapq.heappop(ps)) curr = (curr - (curr // 2)) heapq.heappush(ps, (- curr)) k -= 1 return s...
def get_hit_plots(legend, event): if ((legend is None) or (not legend.is_in(event.x, event.y))): return [] try: label = legend.get_label_at(event.x, event.y) except: raise label = None if (label is None): return [] try: ndx = legend._cached_labels.inde...
def find_missing_dependencies(func: Callable, env: dict) -> Iterator[tuple[(str, list[str])]]: if (env['kind'] != 'virtualenv'): return used_modules = defaultdict(list) scope = {**dill.detect.globalvars(func, recurse=True), **dill.detect.freevars(func)} for (name, obj) in scope.items(): ...
class OFPBundleFeaturesStats(ofproto_parser.namedtuple('OFPBundleFeaturesStats', ('capabilities', 'properties'))): def parser(cls, buf, offset): (capabilities,) = struct.unpack_from(ofproto.OFP_BUNDLE_FEATURES_PACK_STR, buf, offset) properties = [] length = ofproto.OFP_BUNDLE_FEATURES_SIZE ...
class TestUsage(): ('bodhi.server.scripts.initializedb.sys.exit') ('sys.stdout', new_callable=StringIO) def test_usage(self, stdout, exit): initializedb.usage(['initializedb']) assert (stdout.getvalue() == 'usage: initializedb <config_uri>\n(example: "initializedb development.ini")\n') ...
.requires_eclipse .usefixtures('use_tmpdir', 'init_eclrun_config') def test_summary_block(source_root): shutil.copy(os.path.join(source_root, 'test-data/eclipse/SPE1.DATA'), 'SPE1.DATA') econfig = ecl_config.Ecl100Config() erun = ecl_run.EclRun('SPE1.DATA', None) ret_value = erun.summary_block() ass...
_blueprint.route('/flags/<flag_id>/set/<state>', methods=['POST']) _required def set_flag_state(flag_id, state): if (not is_admin()): flask.abort(401) if (state not in ('open', 'closed')): flask.abort(422) flag = models.ProjectFlag.get(Session, flag_id) if (not flag): flask.abort...
.django_db def test_federal_account_loans_invalid_defc(client, generic_account_data, helpers, elasticsearch_account_index, monkeypatch): setup_elasticsearch_test(monkeypatch, elasticsearch_account_index) resp = helpers.post_for_spending_endpoint(client, url, def_codes=['ZZ']) assert (resp.status_code == sta...
class TestBoolean(): def test_accepted_text(self): for text in ('yes', 'y', 'on', 'true', 't', '1'): assert boolean(text) assert boolean(text.upper()) for text in ('no', 'n', 'off', 'false', 'f', '0'): assert (not boolean(text)) assert (not boolean(tex...
class XiAiNovelPageProcessor(HtmlProcessor.HtmlPageProcessor): wanted_mimetypes = ['text/html'] want_priority = 80 loggerPath = 'Main.Text.XiAiNovel' def wantsUrl(url): if re.search('^ url, flags=re.IGNORECASE): print(("XiAiNovel Wants url: '%s'" % url)) return True ...
class LinkedList(): def __init__(self, values=None): values = (values if (values is not None) else []) self._head = None self._len = 0 for value in values: self.push(value) def __iter__(self): return LinkedIterator(self) def __len__(self): return s...
def _makeCostSavingMeasureValues(measure, practice, savings): for i in range(len(savings)): month = (datetime.today() + relativedelta(months=i)) MeasureValue.objects.create(measure=measure, practice=practice, percentile=0.5, cost_savings={'10': (savings[i] * 0.1), '50': savings[i], '90': (savings[i]...
def test_secret_no_group(monkeypatch): plugin_mock = Mock() plugin_mock.secret_requires_group.return_value = False mock_global_plugin = {'plugin': plugin_mock} monkeypatch.setattr(flytekit.configuration.plugin, '_GLOBAL_CONFIG', mock_global_plugin) s = Secret(key='key') assert (s.group is None)
def GetReposAndCurrBranch(params, verbose=True): repos_and_curr_branch = [] def OnOutput(output): stdout = output.stdout.strip() if stdout: repos_and_curr_branch.append((output.repo, stdout)) elif verbose: Print(('Unable to update (could not get current branch for...
def test_bool_convert(): converter = DataType.boolean.value assert (converter.to_value(1) == True) assert (converter.to_value(0) == False) assert (converter.to_value('True') == True) assert (converter.to_value('False') == False) assert (converter.to_value('NOT A BOOLEAN ') is None)
def test_get_latencies_sample(session, request_1, endpoint): interval = DateInterval((datetime.utcnow() - timedelta(days=1)), datetime.utcnow()) requests_criterion = create_time_based_sample_criterion(interval.start_date(), interval.end_date()) data = get_latencies_sample(session, endpoint.id, requests_crit...
class Bridge(): m = {0: {'python': python, 'open': open, 'fileImport': fileImport, 'eval': eval, 'exec': exec, 'setattr': setattr, 'getattr': getattr, 'Iterate': Iterate, 'tuple': tuple, 'set': set, 'enumerate': enumerate, 'repr': repr}} weakmap = WeakValueDictionary() cur_ffid = 0 def __init__(self, ip...
class InnerContainer(): def __init__(self, outer: OuterContainer): self.outer = outer self.inner_icon = Icon(icons.CIRCLE, color=colors.WHITE54, size=100, tooltip='drag me!') self.view = Draggable(group='inner', content=DragTarget(group='inner', content=self.inner_icon, on_accept=self.drag_a...
.unit .parametrize('server_version, cli_version, expected_result', [('1.6.0+7.ge953df5', '1.6.0+7.ge953df5', True), ('1.6.0+7.ge953df5', '1.6.0+9.ge953df5', False), ('1.6.0+7.ge953df5', '1.6.0+7.ge953df5.dirty', True), ('1.6.0+7.ge953df5.dirty', '1.6.0+7.ge953df5', True)]) def test_check_server_version_comparisons(serv...
def find_fmriname(settings, bold_preproc): derivs_layout = get_derivatives_layout(settings.func_derivs_dir) fmriname = derivs_layout.build_path(bold_preproc.entities, '[ses-{session}_]task-{task}[_acq-{acquisition}][_rec-{reconstruction}][_run-{run}][_desc-{desc}]') if ('_run-0' in bold_preproc.path): ...
def notify_outdated_chroots_function(dry_run, email_filter, all): if (not dry_run): dev_instance_warning(email_filter) notifier = (DryRunNotifier() if dry_run else Notifier()) outdated = coprs_logic.CoprChrootsLogic.filter_outdated(coprs_logic.CoprChrootsLogic.get_multiple()) user_chroots_map = ...
def init_test(port, retries): bus = RemoteClient(port=port) bus.open() init_done = False for i in range(retries): bus.regs.sata_phy_enable.write(0) bus.regs.sata_phy_enable.write(1) time.sleep(0.01) if ((bus.regs.sata_phy_status.read() & 1) != 0): init_done = ...
class NotificationContentSchema(NormalSchema): type = fields.Str(dump_only=True) target_type = fields.Str(dump_only=True) target_id = fields.Int(dump_only=True) target_action = fields.Str(dump_only=True) actors = fields.Nested(NotificationActorSchema, many=True) _dump(pass_original=True) def...
class Baz(HasTraits): bar = Instance(Bar) test = Any def _bar_changed(self, obj, old, new): if ((old is not None) and (old is not new)): old.on_trait_change(self._effect_changed, name='effect', remove=True) old.foo.on_trait_change(self._cause_changed, name='cause', remove=Tru...
def get_unpack_status(file_path: str, binary: bytes, extracted_files: List[Path], meta_data: Dict, config: ConfigParser): meta_data['summary'] = [] meta_data['entropy'] = avg_entropy(binary) if ((not extracted_files) and (meta_data.get('number_of_excluded_files', 0) == 0)): if ((get_file_type_from_p...
class TestGymHandler(GymTestCase): is_agent_to_agent_messages = False def test__init__(self): assert (self.gym_handler._task_id is None) def test_setup(self): with patch.object(self.task_manager, 'enqueue_task', return_value=self.mocked_task_id) as mocked_enqueue_task: with patch...
class TraitGridCellAdapter(GridCellEditor): def __init__(self, trait_editor_factory, obj, name, description, handler=None, context=None, style='simple', width=(- 1.0), height=(- 1.0)): super().__init__() self._factory = trait_editor_factory self._style = style self._width = width ...
class btnHeader(QtWidgets.QPushButton): def __init__(self, parent=None): super(btnHeader, self).__init__(parent) self.__parent = parent self.__settings = QSettings(QSettings.NativeFormat, QSettings.UserScope, ORG_NAME, APP_NAME) def mousePressEvent(self, e): self.x0 = e.x() ...
class OptionPlotoptionsColumnrangeSonificationContexttracksMappingHighpass(Options): def frequency(self) -> 'OptionPlotoptionsColumnrangeSonificationContexttracksMappingHighpassFrequency': return self._config_sub_data('frequency', OptionPlotoptionsColumnrangeSonificationContexttracksMappingHighpassFrequency...
.usefixtures('copy_poly_case') def test_case_tool_init_updates_the_case_info_tab(qtbot, storage): config = ErtConfig.from_file('poly.ert') notifier = ErtNotifier(config.config_path) notifier.set_storage(storage) ensemble = storage.create_experiment(parameters=config.ensemble_config.parameter_configurati...
def assert_same_xarray(x, y): assert x.broadcast_equals(y) assert x.equals(y) assert x.identical(y) assert (len(x) == len(y)) assert (set(x.keys()) == set(y.keys())) assert (len(x.dims) == len(y.dims)) assert (len(x.coords) == len(y.coords)) for k in x.keys(): (xda, yda) = (x[k],...
class OptionPlotoptionsVariwideSonificationContexttracksMappingVolume(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 Updater(object): def __init__(self): GIT_REPOSITORY = ' GIT_REPOSITORY2 = ' rootDir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '')) if (not os.path.exists('.git')): print('Not any .git repository found!\n') print(('=' * 30)) ...
class ouraActivitySamples(Base): __tablename__ = 'oura_activity_samples' timestamp_local = Column('timestamp_local', DateTime(), index=True, primary_key=True) summary_date = Column('summary_date', Date()) met_1min = Column('met_1min', Float()) class_5min = Column('class_5min', Integer()) class_5...
class UniqueNameProvider(): def __init__(self): self._name_to_count: Dict[(str, int)] = {} def get_unique_name(self, name: str) -> str: if (name not in self._name_to_count): self._name_to_count[name] = 1 return name else: self._name_to_count[name] += 1...
def extractNirvanatranslationsBlogspotCom(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,...
.parametrize('test_file_high_nonce', ['ttNonce/TransactionWithHighNonce64Minus1.json', 'ttNonce/TransactionWithHighNonce64.json', 'ttNonce/TransactionWithHighNonce64Plus1.json']) def test_high_nonce(test_file_high_nonce: str) -> None: test = load_spurious_dragon_transaction(test_dir, test_file_high_nonce) tx = ...
class TorchStepStateCritic(TorchStateCritic): (StateCritic) def predict_values(self, critic_input: StateCriticInput) -> StateCriticOutput: critic_output = StateCriticOutput() for critic_step_input in critic_input: value = self.networks[critic_step_input.actor_id.step_key](critic_step...
class TestLaunchEndToEnd(AEATestCaseMany): key = 'seller_service' value = None registration_agent_connection = {'delegate_uri': '127.0.0.1:11011', 'entry_peers': [], 'ledger_id': 'fetchai', 'local_uri': '127.0.0.1:9011', 'log_file': 'libp2p_node.log', 'public_uri': '127.0.0.1:9011'} search_agent_connect...
_cache def custom_art(text): img_data = io.BytesIO(b64decode(DEFAULT_ART)) art_img: Image = Image.open(img_data) size = art_img.size x1 = y1 = (size[0] * 0.95) x0 = (x1 - ((len(text) * 0.0625) * size[0])) y0 = (y1 - (0.11 * size[0])) d = ImageDraw.Draw(art_img) try: username = os...
def update(latest_version: str, command: str='py') -> bool: helper.colored_text('Updating...', base=helper.GREEN) try: full_cmd = f'{command} -m pip install --upgrade battle-cats-save-editor=={latest_version}' subprocess.run(full_cmd, shell=True, capture_output=True, check=True) helper.c...
class TestCurrentPrivacyPreference(): def test_get_preference_by_notice_and_fides_user_device(self, db, empty_provided_identity, privacy_preference_history_us_ca_provide_for_fides_user, privacy_notice, privacy_notice_us_ca_provide, fides_user_provided_identity): pref = CurrentPrivacyPreference.get_preferenc...
class TestOptions(BaseOptions): def initialize(self, parser): parser = BaseOptions.initialize(self, parser) parser.add_argument('--results_dir', type=str, default='./results/', help='saves results here.') parser.add_argument('--aspect_ratio', type=float, default=1.0, help='aspect ratio of re...
class OptionPlotoptionsVariwideSonificationDefaultinstrumentoptions(Options): def activeWhen(self) -> 'OptionPlotoptionsVariwideSonificationDefaultinstrumentoptionsActivewhen': return self._config_sub_data('activeWhen', OptionPlotoptionsVariwideSonificationDefaultinstrumentoptionsActivewhen) def instrum...
class TestGetRules(): (scope='function') def url(self, policy: Policy) -> str: return (V1_URL_PREFIX + RULE_CREATE_URI.format(policy_key=policy.key)) def test_get_rules_unauthenticated(self, url, api_client): resp = api_client.get(url) assert (resp.status_code == 401) def test_ge...
('jsonrpcserver.dispatcher.dispatch_request', side_effect=ValueError('foo')) def test_dispatch_to_response_pure_notification_server_error(*_: Mock) -> None: def foo() -> Result: return Success() assert (dispatch_to_response_pure(deserializer=default_deserializer, validator=default_validator, post_proces...
class TestResolverExceptions(): def test_no_env(self, monkeypatch, tmp_path): with monkeypatch.context() as m: m.setattr(sys, 'argv', ['']) with pytest.raises(_SpockFieldHandlerError): config = SpockBuilder(NoEnv, desc='Test Builder') config.generate()...
def _execute(cmd, stdin=None, stderr_to_stdout=False): logger.log(IMPORTANT, 'Running command (panel): %s', cmd) if stderr_to_stdout: stderr = STDOUT else: stderr = PIPE proc = Popen(cmd, bufsize=0, close_fds=True, stdout=PIPE, stderr=stderr, stdin=PIPE) (stdout, stderr) = proc.commu...
def upgrade(): op.add_column('sessions', sa.Column('creator_id', sa.Integer(), nullable=True)) op.create_foreign_key(None, 'sessions', 'users', ['creator_id'], ['id'], ondelete='CASCADE') op.add_column('sessions_version', sa.Column('creator_id', sa.Integer(), autoincrement=False, nullable=True)) op.exec...
def test_for_loop_variable_generation(): renamer = ForLoopVariableRenamer(AbstractSyntaxTree(SeqNode(LogicCondition.initialize_true(LogicCondition.generate_new_context())), {}), ['i', 'j', 'k', 'l', 'm', 'n']) assert ([renamer._get_variable_name() for _ in range(14)] == ['i', 'j', 'k', 'l', 'm', 'n', 'i1', 'j1'...
class OptionPlotoptionsItemSonificationDefaultinstrumentoptionsMappingVolume(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: s...
class TestExplainerAccessByResource(): .client .e2e .explainer def test_access_by_resource_for_organization(self, forseti_cli: ForsetiCli, forseti_model_readonly, forseti_server_service_account, organization_id): (model_name, _, _) = forseti_model_readonly forseti_cli.model_use(model_nam...
def writePiecesArrays(save): for i in range(len(globVar.w_pieces)): save.write(str(globVar.w_pieces[i].color)) save.write(',') save.write(str(globVar.w_pieces[i].selected)) save.write(',') save.write(str(globVar.w_pieces[i].type)) save.write(',') save.write(st...
class icmptype_ContentHandler(IO_Object_ContentHandler): def startElement(self, name, attrs): IO_Object_ContentHandler.startElement(self, name, attrs) self.item.parser_check_element_attrs(name, attrs) if (name == 'icmptype'): if ('name' in attrs): log.warning(("Ig...
class Plotly3D(): def __init__(self, ui): self.page = ui.page self.chartFamily = 'Plotly' def scatter(self, record, y_columns=None, x_axis=None, z_axis=None, profile=None, options=None, width=(100, '%'), height=(500, 'px'), html_code=None): options = (options or {}) options.updat...
class PluginRunner(): class Config(BaseModel): process_count: int timeout: int class Task(BaseModel): virtual_file_path: typing.Dict path: str dependencies: typing.Dict scheduler_state: FileObject model_config = ConfigDict(arbitrary_types_allowed=True) ...
def test_config_snapshotting_span_compression_drop_exit_span(elasticapm_client): elasticapm_client.config.update(version='1', exit_span_min_duration='10ms') elasticapm_client.begin_transaction('foo') elasticapm_client.config.update(version='2', exit_span_min_duration='0ms') with elasticapm.capture_span(...
class OptionSeriesBulletSonificationTracks(Options): def activeWhen(self) -> 'OptionSeriesBulletSonificationTracksActivewhen': return self._config_sub_data('activeWhen', OptionSeriesBulletSonificationTracksActivewhen) def instrument(self): return self._config_get('piano') def instrument(self...
class OptionSeriesSankeyOnpointConnectoroptions(Options): def dashstyle(self): return self._config_get(None) def dashstyle(self, text: str): self._config(text, js_type=False) def stroke(self): return self._config_get(None) def stroke(self, text: str): self._config(text, j...
def _parent_SK_to_lamport_PK(*, parent_SK: int, index: int) -> bytes: salt = index.to_bytes(4, byteorder='big') IKM = parent_SK.to_bytes(32, byteorder='big') lamport_0 = _IKM_to_lamport_SK(IKM=IKM, salt=salt) not_IKM = _flip_bits_256(parent_SK).to_bytes(32, byteorder='big') lamport_1 = _IKM_to_lampo...
def to_actions(dp, acts): inst = [] actions = [] ofp = dp.ofproto parser = dp.ofproto_parser for a in acts: action = to_action(dp, a) if (action is not None): actions.append(action) else: action_type = a.get('type') if (action_type == 'WRIT...
def perform_rollout_seeding_test(hydra_overrides_sequential: Dict[(str, str)], hydra_overrides_parallel: Dict[(str, str)]) -> None: sequential_writer = LogStatsWriterExtract() register_log_stats_writer(sequential_writer) hydra_overrides_sequential.update({'runner': 'sequential', 'runner.n_episodes': 8}) ...
class OptionPlotoptionsWordcloudSonificationDefaultinstrumentoptionsMappingHighpassResonance(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 map...
class Migration(migrations.Migration): initial = True dependencies = [] operations = [migrations.CreateModel(name='SourceAssistanceTransaction', fields=[('published_award_financial_assistance_id', models.IntegerField(help_text='surrogate primary key defined in Broker', primary_key=True, serialize=False)), (...
def upgrade(): op.drop_constraint(u'call_for_papers_event_id_fkey', 'call_for_papers', type_='foreignkey') op.create_foreign_key(None, 'call_for_papers', 'events', ['event_id'], ['id'], ondelete='CASCADE') op.drop_constraint(u'custom_forms_event_id_fkey', 'custom_forms', type_='foreignkey') op.create_fo...
class TestLedgerApiHandler(BaseSkillTestCase): path_to_skill = Path(ROOT_DIR, 'packages', 'fetchai', 'skills', 'ml_data_provider') is_agent_to_agent_messages = False def setup(cls): super().setup() cls.ledger_api_handler = cast(LedgerApiHandler, cls._skill.skill_context.handlers.ledger_api) ...
.parametrize('date, name, fracture', itertools.product([, ], ['SGAS', 'SOIL', 'SWAT'], [True, False])) def test_dual_runs_restart_property_to_file(dual_runs, date, name, fracture): prop = dual_runs.get_property_from_restart(name, date=date, fracture=fracture) if fracture: assert (prop.name == f'{name}F_...
('value,expected', [param('abc', 'abc', id='value:simple'), param('abc ', 'abc', id='value:simple_ws'), param(' abc', 'abc', id='ws_value:simple'), param('[1,2,3]', [1, 2, 3], id='value:list'), param('[1 ]', [1], id='value:list1_ws'), param('[1, 2, 3]', [1, 2, 3], id='value:list_ws'), param('1,2,3', ChoiceSweep(list=[1...
def create_2d_list(text: str) -> list: lines = text.strip().split('\n') (result, sublist) = ([], []) for (i, line) in enumerate(lines): if (line.strip() == ''): continue if (((i % 7) == 0) and sublist): result.append(sublist) sublist = [] sublist.a...
class SkillComponentTestCase(TestCase): def setUp(self): class TestComponent(SkillComponent): def parse_module(self, *args): pass def setup(self, *args): pass def teardown(self, *args): pass self.TestComponent = Test...
def Oranges(range, **traits): _data = dict(red=[(0.0, 1.0, 1.0), (0.125, 0., 0.), (0.25, 0., 0.), (0.375, 0., 0.), (0.5, 0., 0.), (0.625, 0., 0.), (0.75, 0., 0.), (0.875, 0., 0.), (1.0, 0., 0.)], green=[(0.0, 0., 0.), (0.125, 0., 0.), (0.25, 0., 0.), (0.375, 0., 0.), (0.5, 0., 0.), (0.625, 0., 0.), (0.75, 0., 0.), ...
def get_last_invocation(region, args, function_name): logs_client = init_boto_client('logs', region, args) last_invocation = (- 1) try: logs = logs_client.describe_log_streams(logGroupName='/aws/lambda/{0}'.format(function_name), orderBy='LastEventTime', descending=True) except ClientError as _:...
def upper_key(letter): if (len(letter) != 1): return ' ' custom_alpha = {'': '', '|': '', '<': '', '>': '', '': '', '': '', '': '', '': '', '': '', '': ' '} if (letter in custom_alpha): return custom_alpha[letter] if (letter.upper() != letter.lower()): return letter.upper() r...
def is_plugged_in(throw_error=True): if (platform.system() == 'Windows'): if (not GetSystemPowerStatus(ctypes.pointer(powerStatus))): if throw_error: raise RuntimeError('could not get power status') return False return (powerStatus.ACLineStatus == 1) retur...
class DefaultSchema(ViewInspector): def __get__(self, instance, owner): result = super().__get__(instance, owner) if (not isinstance(result, DefaultSchema)): return result inspector_class = api_settings.DEFAULT_SCHEMA_CLASS assert issubclass(inspector_class, ViewInspector...
class OptionSeriesOrganizationSonificationDefaultinstrumentoptionsMappingPitch(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: ...
class OptionPlotoptionsWaterfallSonificationDefaultspeechoptionsActivewhen(Options): def crossingDown(self): return self._config_get(None) def crossingDown(self, num: float): self._config(num, js_type=False) def crossingUp(self): return self._config_get(None) def crossingUp(self,...
def _transform_bad_request_response_to_exception(response): if ((response.status_code == requests.codes.bad) and (response.json()['errorName'] == 'FoundrySqlServer:InvalidDatasetNoSchema')): raise DatasetHasNoSchemaError('SQL') if ((response.status_code == requests.codes.bad) and (response.json()['error...
_admin_groups.command() _context def execute(ctx): options = '[*] Available options\n[1] Load harvested groups from json file and check their assigned roles for administrator permissions\n[2] Harvest all groups and check their assigned roles for administrator permissions\n[0] Exit this menu\n[*] Choose from the abo...
def test(): assert (len(pattern1) == 2), "The number of tokens in pattern1 doesn't match the real number of tokens in the string." assert (len(pattern2) == 4), "The number of tokens in pattern2 doesn't match the real number of tokens in the string." assert (len(pattern1[0]) == 1), 'The first token of patter...
def plot_curve_wrt_time(ax, records, x_wrt_sth, y_wrt_sth, xlabel, ylabel, title=None, markevery_list=None, is_smooth=True, smooth_space=100, l_subset=0.0, r_subset=1.0, reorder_record_item=None, remove_duplicate=True, legend=None, legend_loc='lower right', legend_ncol=2, bbox_to_anchor=[0, 0], ylimit_bottom=None, ylim...
def _is_valid_optional(content_type: str) -> bool: content_type = content_type.strip() if (not content_type.startswith('pt:optional')): return False if (not _has_matched_brackets(content_type)): return False if (not _has_brackets(content_type)): return False sub_types = _get_...
class OptionPlotoptionsPackedbubbleStates(Options): def hover(self) -> 'OptionPlotoptionsPackedbubbleStatesHover': return self._config_sub_data('hover', OptionPlotoptionsPackedbubbleStatesHover) def inactive(self) -> 'OptionPlotoptionsPackedbubbleStatesInactive': return self._config_sub_data('in...
def feed(): global hunger, sick if (hunger <= 88): if (sick == True): hunger += (HUNGER_ADD // 2) _thread.start_new_thread(updateLabel, (3, (TAMA_NAME + " doesn't want to eat."))) else: hunger += HUNGER_ADD else: _thread.start_new_thread(updateLabe...
class AdDynamicCreative(AbstractObject): def __init__(self, api=None): super(AdDynamicCreative, self).__init__() self._isAdDynamicCreative = True self._api = api class Field(AbstractObject.Field): preview_url = 'preview_url' _field_types = {'preview_url': 'string'} def _g...
def _parse_signed_tx(signed_tx: HexBytes) -> TxParams: tx_type = signed_tx[0] if (tx_type > int('0x7f', 16)): decoded_tx = rlp.decode(signed_tx, Transaction).as_dict() else: if (tx_type == 1): sedes = AccessListTransaction._signed_transaction_serializer elif (tx_type == 2...
def export_hdf5_well(self, wfile, compression='lzf'): logger.debug('Export to hdf5 format...') self._ensure_consistency() self.metadata.required = self meta = self.metadata.get_metadata() jmeta = json.dumps(meta) complib = 'zlib' complevel = 5 if (compression and (compression == 'blosc')...
def dump(obj, nested_level=0, output=sys.stdout): spacing = ' ' if (type(obj) == dict): ((print >> output), ('%s{' % (nested_level * spacing))) for (k, v) in obj.items(): if hasattr(v, '__iter__'): ((print >> output), ('%s%s:' % (((nested_level + 1) * spacing), k)))...
def test_conversion_of_ai_standard_to_red_shift_material_bump_properties(create_pymel, setup_scene): pm = create_pymel (ai_standard, ai_standard_sg) = pm.createSurfaceShader('aiStandard') file_node = pm.shadingNode('file', asTexture=1) bump2d_node = pm.shadingNode('bump2d', asUtility=1) file_node.ou...