code
stringlengths
281
23.7M
def _create_temporary_connection(): connect = SQLiteTempConnect.create_temporary_db() connect.create_temp_tables({'user': {'columns': {'id': 'INTEGER PRIMARY KEY', 'name': 'TEXT', 'age': 'INTEGER'}, 'data': [(1, 'Tom', 10), (2, 'Jerry', 16), (3, 'Jack', 18), (4, 'Alice', 20), (5, 'Bob', 22)]}}) return conne...
.parametrize('value,expected', [([, 'wei'], ''), ([, 'kwei'], ''), ([, 'mwei'], ''), ([, 'gwei'], ''), ([, 'szabo'], '1000000'), ([, 'finney'], '1000'), ([, 'ether'], '1'), ([, 'kether'], '0.001'), ([, 'grand'], '0.001'), ([, 'mether'], '0.000001'), ([, 'gether'], '0.'), ([, 'tether'], '0.')]) def test_from_wei(value, ...
def list(fips_dir, proj_dir, pattern): dirs = get_config_dirs(fips_dir, proj_dir) res = OrderedDict() for curDir in dirs: res[curDir] = [] paths = glob.glob('{}/*.yml'.format(curDir)) for path in paths: fname = os.path.split(path)[1] fname = os.path.splitext(f...
class TestAtLeastOneCheckboxIsChecked(unittest.TestCase): def setUp(self): self.not_empty_messages = {'missing': 'a missing value message'} class CheckForCheckboxSchema(Schema): agree = validators.StringBool(messages=self.not_empty_messages) self.schema = CheckForCheckboxSchema()...
def draw_overlapped_ways(types: list[dict[(str, str)]], path: Path) -> None: grid: Grid = Grid() for (index, tags) in enumerate(types): node_1: OSMNode = grid.add_node({}, 8, (index + 1)) node_2: OSMNode = grid.add_node({}, (len(types) + 9), (index + 1)) grid.add_way(tags, [node_1, node_...
def prompt_password(ctx: click.Context, param: str, value: str) -> str: config_value = ctx.obj['CONFIG'].user.password if value: return value if config_value: click.echo('> Password found in configuration.') return config_value value = click.prompt(text='Password', hide_input=Tru...
class TestPrometheusConnection(): def setup(self): self.metrics = {} configuration = ConnectionConfig(connection_id=PrometheusConnection.connection_id, port=9090) self.some_skill = 'some/skill:0.1.0' self.agent_address = 'my_address' self.agent_public_key = 'my_public_key' ...
def make(apps, apks, repodir, archive): from fdroidserver.update import METADATA_VERSION if ((not hasattr(common.options, 'nosign')) or (not common.options.nosign)): common.assert_config_keystore(common.config) sortedids = sorted(apps, key=(lambda appid: common.get_app_display_name(apps[appid]).uppe...
def upgrade(): op.create_table('event_sub_topics', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(), nullable=False), sa.Column('slug', sa.String(), nullable=False), sa.Column('event_topic_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['event_topic_id'], ['event_topics.id'],...
class ComparerTopimage(): def extract(self, item, list_article_candidate): list_topimage = [] for article_candidate in list_article_candidate: if (article_candidate.topimage is not None): article_candidate.topimage = self.image_absoulte_path(item['url'], article_candidate...
class TestGetAlgBW(unittest.TestCase): def test_no_iterations(self): elapsedTimeNs = 30000 dataSize = 90000 numIters = 0 (avgIterNS, algBW) = comms_utils.getAlgBW(elapsedTimeNs, dataSize, numIters) self.assertEqual(0.0, avgIterNS, algBW) def test_iterations(self): ...
def zernike_to_noll(n, m): i = (int(((((n + 0.5) ** 2) + 1) / 2)) + 1) Nn = ((((n + 1) * (n + 2)) // 2) + 1) for j in range(i, (i + Nn)): (nn, mm) = noll_to_zernike(j) if ((nn == n) and (mm == m)): return j raise ValueError(('Could not find noll index for (%d,%d)' % n), m)
class Acordeon(AssetClr): name = 'clr-accordeon' def __str__(self): return '\n<clr-accordion>\n <clr-accordion-panel>\n <clr-accordion-title>Item 1</clr-accordion-title>\n <clr-accordion-content *clrIfExpanded>Content 1</clr-accordion-content>\n </clr-accordion-panel>\n</clr-accordion>\n'
class _WSContextManager(): def __init__(self, ws, task_req): self._ws = ws self._task_req = task_req async def __aenter__(self): ready_waiter = create_task(self._ws.wait_ready()) (await asyncio.wait([ready_waiter, self._task_req], return_when=asyncio.FIRST_COMPLETED)) if ...
class OptionPlotoptionsScatterDragdropGuideboxDefault(Options): def className(self): return self._config_get('highcharts-drag-box-default') def className(self, text: str): self._config(text, js_type=False) def color(self): return self._config_get('rgba(0, 0, 0, 0.1)') def color(s...
class OptionPlotoptionsFunnel3dSonificationContexttracksMappingHighpass(Options): def frequency(self) -> 'OptionPlotoptionsFunnel3dSonificationContexttracksMappingHighpassFrequency': return self._config_sub_data('frequency', OptionPlotoptionsFunnel3dSonificationContexttracksMappingHighpassFrequency) def...
class ChannelBase(object): def __init__(self, function_control, name, rgb_color, channel_index, channel_mode): self.control = function_control self.name = name self.rgb_color = rgb_color self.index = channel_index self.mode = channel_mode def get_value(self, color): ...
_ns.route('/<username>/<coprname>/module/<id>') _ns.route('/g/<group_name>/<coprname>/module/<id>') _with_copr def copr_module(copr, id): module = ModulesLogic.get(id).first() formatter = HtmlFormatter(style='autumn', linenos=False, noclasses=True) pretty_yaml = highlight(module.yaml, get_lexer_by_name('YAM...
class Text3D(ModuleFactory): _target = Instance(modules.Text3D, ()) scale = Either(CFloat(1), CArray(shape=(3,)), help='The scale of the text, in figure units.\n Either a float, or 3-tuple of floats.') orientation = CArray(shape=(3,), adapts='orientation', desc='the angles giv...
class Mondriaan(flx.Widget): CSS = '\n .flx-Mondriaan {background: #000;}\n .flx-Mondriaan .edge {background:none;}\n .flx-Mondriaan .white {background:#fff;}\n .flx-Mondriaan .red {background:#f23;}\n .flx-Mondriaan .blue {background:#249;}\n .flx-Mondriaan .yellow {background:#ff7;}\n ' d...
def downgrade(): with op.batch_alter_table('user') as batch_op: batch_op.alter_column('id', existing_type=sqlalchemy_utils.types.uuid.UUIDType(), type_=sa.NUMERIC(precision=16), existing_nullable=False) with op.batch_alter_table('templates') as batch_op: batch_op.alter_column('id', existing_type...
_required _required _required _POST def alert_list_table(request): context = collect_view_data(request, 'mon_alert_list') try: api_data = json.loads(request.POST.get('alert_filter', None)) except (ValueError, TypeError): context['error'] = 'Unexpected error: could not parse alert filter.' ...
def get_channel_videos(channel_id): res = youtube_client.channels().list(id=channel_id, part='contentDetails').execute() videos = {} for item in res['items']: playlist_id = item['contentDetails']['relatedPlaylists']['uploads'] res = youtube_client.playlistItems().list(playlistId=playlist_id,...
class TestTimeField(FieldValues): valid_inputs = {'13:00': datetime.time(13, 0), datetime.time(13, 0): datetime.time(13, 0)} invalid_inputs = {'abc': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]].'], '99:99': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[....
class QueueTrigger(WebMirror.TimedTriggers.TriggerBase.TriggerBaseClass, WebMirror.JobDispatcher.RpcMixin): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.check_open_rpc_interface() def get_create_job(self, sess, url): have = sess.query(self.db.WebPages).filt...
def test_validate_generator(): _registry.schedules('test_schedule.v2') def test_schedule(): while True: (yield 10) cfg = {'': 'test_schedule.v2'} result = my_registry.resolve({'test': cfg})['test'] assert isinstance(result, GeneratorType) _registry.optimizers('test_optimizer....
def test_auth_role(): obj = _common.AuthRole(assumable_iam_role='rollie-pollie') assert (obj.assumable_iam_role == 'rollie-pollie') assert (not obj.kubernetes_service_account) obj2 = _common.AuthRole.from_flyte_idl(obj.to_flyte_idl()) assert (obj == obj2) obj = _common.AuthRole(kubernetes_servic...
class IPFSGatewayBackend(IPFSOverHTTPBackend): def base_uri(self) -> str: return IPFS_GATEWAY_PREFIX def pin_assets(self, file_or_dir_path: Path) -> List[Dict[(str, str)]]: raise CannotHandleURI('IPFS gateway is currently disabled, please use a different IPFS backend.') def fetch_uri_content...
def test_reset_last_overriding(): class _Container(containers.DeclarativeContainer): p11 = providers.Provider() class _OverridingContainer1(containers.DeclarativeContainer): p11 = providers.Provider() class _OverridingContainer2(containers.DeclarativeContainer): p11 = providers.Provi...
class Container(containers.DeclarativeContainer): wiring_config = containers.WiringConfiguration(modules=['.handlers']) config = providers.Configuration(yaml_files=['config.yml']) giphy_client = providers.Factory(giphy.GiphyClient, api_key=config.giphy.api_key, timeout=config.giphy.request_timeout) sear...
class TestSnippetDedent(util.MdCase): extension = ['pymdownx.snippets', 'pymdownx.superfences'] extension_configs = {'pymdownx.snippets': {'base_path': [os.path.join(BASE, '_snippets')], 'dedent_subsections': True}} def test_dedent_section(self): self.check_markdown('\n ```text\n ...
class CacheBackend(CacheBackendT, Service): logger = logger Unavailable: Type[BaseException] = CacheUnavailable operational_errors: ClassVar[Tuple[(Type[BaseException], ...)]] = () invalidating_errors: ClassVar[Tuple[(Type[BaseException], ...)]] = () irrecoverable_errors: ClassVar[Tuple[(Type[BaseEx...
.benchmark def test_baker_gs_opt_synthesis(fixture_store): for (i, fix) in enumerate(fixture_store): print(i, fix) tot_cycles = 0 converged = 0 bags = fixture_store['results_bag'] for (k, v) in bags.items(): if (not k.startswith('test_baker_gs_opt')): continue pri...
def test_adding_a_node_affinity(): config = '\nnodeAffinity:\n preferredDuringSchedulingIgnoredDuringExecution:\n - weight: 100\n preference:\n matchExpressions:\n - key: mylabel\n operator: In\n values:\n - myvalue\n' r = helm_template(config) assert (r['statefulset'][na...
def main(): (ref_get_time, ref_set_time) = new_style_value().measure() benchmarks = [global_value, old_style_value, new_style_value, property_value, any_value, int_value, range_value, change_value, monitor_value, delegate_value, delegate_2_value, delegate_3_value] for benchmark in benchmarks: run_be...
class OptionPlotoptionsPackedbubbleSonificationTracksMappingLowpass(Options): def frequency(self) -> 'OptionPlotoptionsPackedbubbleSonificationTracksMappingLowpassFrequency': return self._config_sub_data('frequency', OptionPlotoptionsPackedbubbleSonificationTracksMappingLowpassFrequency) def resonance(s...
def _invalidate_thread_cache(s: Session, old_thread: ThreadModel, board: BoardModel): key = cache_key('thread', board.name, old_thread.refno) stub_key = cache_key('thread_stub', board.name, old_thread.refno) old_thread_posts_cache = cache.get(key) old_thread_posts = None if old_thread_posts_cache: ...
class InferenceGraph(): def __init__(self, inference_block: InferenceBlock): self.perception_blocks = inference_block.perception_blocks self.node_graph = nx.DiGraph() out_keys = inference_block.out_keys self.in_key_shapes = dict() self._total_num_of_params = self._get_num_of_...
class LinguaMakoExtractor(Extractor, MessageExtractor): extensions = ['.mako'] default_config = {'encoding': 'utf-8', 'comment-tags': ''} def __call__(self, filename, options, fileobj=None): self.options = options self.filename = filename self.python_extractor = get_extractor('x.py')...
.parametrize('fork_version, valid, result', [((b'\x12' * 4), True, b'\x03\x00\x00\x00\rf`\x8a\xf5W\xf4\xfa\xdb\xfc\xe2H\xac7\xf6\xe7c\x9c\xe3q\x10\x0cC\xd1Z\xad\x05\xcb'), ((b'\x12' * 5), False, None), ((b'\x12' * 3), False, None)]) def test_compute_deposit_domain(fork_version, valid, result): if valid: ass...
def Run(params): args = params.args config_file = params.config_file config = params.config if (len(args) < 2): msg = 'Repository (dir name|--all|--current|--recursive) to track not passed' Print(msg) return Status(msg, False) repos = config.repos msgs = [] args = arg...
class bsn_stats_reply(experimenter_stats_reply): subtypes = {} version = 4 type = 19 stats_type = 65535 experimenter = 6035143 def __init__(self, xid=None, flags=None, subtype=None): if (xid != None): self.xid = xid else: self.xid = None if (flags ...
class IndexCreator(): def __init__(self): self.inames = OrderedDict() self.namer = UniqueNameGenerator(forced_prefix='i_') def __call__(self, extents): extents += ((1,) if (len(extents) == 0) else ()) indices = [] if isinstance(extents[0], tuple): for ext_per_...
(scope='module') def stabilityai_sdxl_base_path(test_weights_path: Path) -> Path: r = ((test_weights_path / 'stabilityai') / 'stable-diffusion-xl-base-1.0') if (not r.is_dir()): warn(f'could not find Stability SDXL base weights at {r}, skipping') pytest.skip(allow_module_level=True) return r
class ReplyForm(PostForm): track_topic = BooleanField(_('Track this topic'), default=False, validators=[Optional()]) def __init__(self, *args, **kwargs): self.post = kwargs.get('obj', None) PostForm.__init__(self, *args, **kwargs) def save(self, user, topic): if (self.post is None): ...
((MAGICK_VERSION_NUMBER < 1802), reason='Minimum Bounding Box requires ImageMagick-7.0.10.') def test_minimum_bounding_box(): with Image(filename='wizard:') as img: img.fuzz = (0.1 * img.quantum_range) img.background_color = 'white' mbr = img.minimum_bounding_box() assert (img.width ...
class OptionSeriesSunburstSonificationDefaultinstrumentoptionsMappingHighpass(Options): def frequency(self) -> 'OptionSeriesSunburstSonificationDefaultinstrumentoptionsMappingHighpassFrequency': return self._config_sub_data('frequency', OptionSeriesSunburstSonificationDefaultinstrumentoptionsMappingHighpass...
def main(): p = argparse.ArgumentParser() p.add_argument('--gpu', '-g', type=int, default=(- 1)) p.add_argument('--pretrained_model', '-P', type=str, default='baseline.pth') p.add_argument('--input', '-i', required=True) p.add_argument('--output_dir', '-o', type=str, default='') p.add_argument('...
class TestFrontendClient(object): def _get_fake_response(): resp = Munch() resp.headers = {'Copr-FE-BE-API-Version': '666'} resp.status_code = 200 resp.data = 'ok\n' return resp def setup_method(self, method): self.opts = Munch(frontend_base_url=' frontend_auth=''...
class TestVOF(object): def setup_class(cls): pass def teardown_class(cls): pass def setup_method(self, method): reload(default_n) reload(thelper_vof) self.pList = [thelper_vof_p] self.nList = [thelper_vof_n] self.sList = [default_s] self.so = d...
class FlashbotsPrivateTransactionResponse(): w3: Web3 tx: SignedTxAndHash max_block_number: int def __init__(self, w3: Web3, signed_tx: HexBytes, max_block_number: int): self.w3 = w3 self.max_block_number = max_block_number self.tx = {'signed_transaction': signed_tx, 'hash': self...
class IODict(BaseDict): def __init__(self, *args, **kwargs): if (len(args) == 1): arg = args[0] if (type_util.is_string(arg) or type_util.is_path(arg)): d = IODict._decode_init(arg, **kwargs) super().__init__(d) return super()._...
def extractChocolateotakuWordpressCom(item): badwords = ['Rant', 'Rants', 'review'] if any([(bad in item['tags']) for bad in badwords]): return None (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): ...
class TunerPayload(BasePayload): def __init__(self, s3_config: Optional[_T]=None): super().__init__(s3_config=s3_config) def _update_payload(base_payload, input_classes, ignore_classes, payload): attr_fields = get_attr_fields(input_classes=input_classes) ignore_fields = get_attr_fields(i...
def extractBlessedmangoWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('sss_architect', 'Expelled SSS-rank architect, rebuilding the demon kings castle!', 'translat...
def get_image_widget(duration: float, width: int, height: int, filename: str, pkg: typing.Optional[str]=None, start_at: float=BEGINNING, position: POSITION_T=RANDOM) -> Stimulus: position = get_position(position, (width, height)) return QtStimulus(start_at=start_at, duration=duration, qt_type='QLabelWithPicture...
('ecs_deploy.cli.get_client') def test_deploy_change_environment_variable_empty_string(get_client, runner): get_client.return_value = EcsTestClient('acces_key', 'secret_key') result = runner.invoke(cli.deploy, (CLUSTER_NAME, SERVICE_NAME, '-e', 'application', 'foo', '')) assert (result.exit_code == 0) a...
.django_db def test_primitives(): data_types = OrderedDict([('test', primatives.ColumnDefinition(name='test', data_type='int', not_nullable=True)), ('tube', primatives.ColumnDefinition(name='tube', data_type='text', not_nullable=False))]) single_key_column = [data_types['test']] double_key_column = [data_ty...
class TestArchChecker(unittest.TestCase): def __init__(self, *args, **kwargs): logSetup.initLogging() super().__init__(*args, **kwargs) self.maxDiff = None def setUp(self): self.addCleanup(self.dropDatabase) self.db = Tests.basePhashTestSetup.TestDb() self.verifyD...
.requires_eclipse def test_failed_run(init_ecl100_config, source_root): shutil.copy((source_root / 'test-data/eclipse/SPE1_ERROR.DATA'), 'SPE1_ERROR.DATA') econfig = ecl_config.Ecl100Config() sim = econfig.sim('2019.3') erun = ecl_run.EclRun('SPE1_ERROR', sim) with pytest.raises(RuntimeError, match=...
class Banheiro(): def __init__(self): self.it = [] def entrar(self, obj): self.it.append(obj) def sair(self, pos=0): return self.it.pop(pos) def __len__(self): return len(self.it) def __contains__(self, obj): return (obj in self.it) def __repr__(self): ...
def run_test(thr, shape, dtype, axes=None): data = numpy.random.normal(size=shape).astype(dtype) fft = FFT(data, axes=axes) fftc = fft.compile(thr) shift = FFTShift(data, axes=axes) shiftc = shift.compile(thr) data_dev = thr.to_device(data) t_start = time.time() fftc(data_dev, data_dev) ...
class OptionPlotoptionsParetoSonificationContexttracksMappingRate(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 LegacyKeylist(Keylist): def __init__(self, keylist): super(LegacyKeylist, self).__init__(keylist.c) self.original_keylist = keylist self.c = keylist.c self.fingerprint = keylist.fingerprint self.url = keylist.url self.keyserver = keylist.keyserver self.u...
class FandoghCommand(Command): def invoke(self, ctx): try: self._check_for_new_version() self._check_for_error_collection_permission() return super(FandoghCommand, self).invoke(ctx) except CommandParameterException as exp: click.echo(format_text(exp.me...
_frequency(timedelta(days=1)) def fetch_price(zone_key: str='TR', session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> list: if (target_datetime is None): target_datetime = datetime.now(tz=TR_TZ) data = fetch_data(target_datetime=target_datetime...
class OptionPlotoptionsDumbbellEvents(Options): def afterAnimate(self): return self._config_get(None) def afterAnimate(self, value: Any): self._config(value, js_type=False) def checkboxClick(self): return self._config_get(None) def checkboxClick(self, value: Any): self._c...
class OptionPlotoptionsDependencywheelAccessibility(Options): def description(self): return self._config_get(None) def description(self, text: str): self._config(text, js_type=False) def descriptionFormat(self): return self._config_get(None) def descriptionFormat(self, text: str)...
.skipif((not has_hf_transformers), reason='requires huggingface transformers') .parametrize('model', _FRENCH_MODELS) def test_against_hf_tokenizers_french(model, french_sample_texts): compare_tokenizer_outputs_with_hf_tokenizer(french_sample_texts, model.model, Tokenizer, pad_token=model.pad_token)
class TestProcessValue(object): def setting_info1(self): return {'value_type': 'rgbgradientv2', 'rgbgradientv2_header': {'color_field_length': 139, 'duration_length': 2, 'maxgradient': 14}, 'led_id': 2} .parametrize('color', ['#FF2200', '#ff2200', 'FF2200', 'ff2200', '#F20', '#f20', 'F20', 'f20']) d...
class MORXRearrangementTest(unittest.TestCase): def setUpClass(cls): cls.maxDiff = None cls.font = FakeFont(['.nodef', 'A', 'B', 'C']) def test_decompile_toXML(self): table = newTable('morx') table.decompile(MORX_REARRANGEMENT_DATA, self.font) self.assertEqual(getXML(tabl...
(cls=ClickAliasedGroup, help=cmd_help) ('-v', '--verbose', help='Enable verbose logging.', is_flag=True, default=False) def cli(**options: Dict[(str, Any)]) -> None: if options['verbose']: level = logging.DEBUG fmt = '[%(asctime)s] [%(name)s:%(lineno)d] [%(levelname)s] %(message)s' else: ...
class Components(): def __init__(self, page): self.page = page if (self.page.ext_packages is None): self.page.ext_packages = {} self.page.ext_packages.update(PkgImports.CLARITY) self.page.cssImport.add('/core') self.page.cssImport.add('/city') self.page.bo...
_required def UserEdit(request, username): profile = UserProfile.objects.get(user__username=username) user = User.objects.get(username=username) if (not (request.user.is_authenticated() and (request.user.id == user.id))): messages.add_message(request, messages.INFO, 'You cannot edit this profile') ...
class UploadFile(): def __init__(self, file): self.file = file self.file_extension = self.get_extension() if self.file_extension: self.file_name = self.random_filename(self.file.filename, characters=8) else: self.file_name = None self.upload_folder = N...
class ConfigDictGenerator(): serial = 0 def create_config_dict(file_name): with open(file_name, 'r+', encoding='utf-8') as config_file: bogus_values = [] for value in config_file.readlines(): bogus_values.append(('%s' % value[1:2])) for value in V2_TOP...
def upgrade(): c = get_context() insp = sa.inspect(c.connection.engine) groups_permissions_pkey = 'groups_permissions_pkey' groups_pkey = 'groups_pkey' groups_resources_permissions_pkey = 'groups_resources_permissions_pkey' users_groups_pkey = 'users_groups_pkey' users_permissions_pkey = 'us...
class OptionPlotoptionsItemMarkerStates(Options): def hover(self) -> 'OptionPlotoptionsItemMarkerStatesHover': return self._config_sub_data('hover', OptionPlotoptionsItemMarkerStatesHover) def normal(self) -> 'OptionPlotoptionsItemMarkerStatesNormal': return self._config_sub_data('normal', Optio...
def test_deployment_config(dashboard_user, config): response = dashboard_user.get('dashboard/api/deploy_config') assert (response.status_code == 200) data = response.json assert (data['database_name'] == config.database_name) assert (data['outlier_detection_constant'] == config.outlier_detection_con...
class SchedulerBaseTester(unittest.TestCase): def setUp(self): super(SchedulerBaseTester, self).setUp() from stalker import Studio self.test_studio = Studio(name='Test Studio') self.kwargs = {'studio': self.test_studio} self.test_scheduler_base = SchedulerBase(**self.kwargs) ...
def get_location(location_slug): if location_slug: try: location = Location.objects.filter(slug=location_slug).first() except: raise LocationDoesNotExistException(('The requested location does not exist: %s' % location_slug)) elif (Location.objects.count() == 1): ...
def character_aware_flip90(art: str) -> str: art_lines = art.split('\n') art_char_list = [[(flip90_character_alternatives[char] if (char in flip90_character_alternatives.keys()) else char) for char in list(line)] for line in art_lines] char_list_flipped = list(map(list, zip(*art_char_list))) output = ''...
def new_table_from_expr(name, expr, const, temporary): assert isinstance(name, Id) elems = expr.type.elems if any(((t <= T.unknown) for t in elems.values())): return objects.TableInstance.make(sql.null, expr.type, []) if (('id' in elems) and (not const)): msg = "Field 'id' already exists...
class js_search_data(): def __init__(self): self.children: list = [] self.parent: js_data = None self.after = None self.before = None self.data = None def __repr__(self): return json.dumps(self.children) def to_list(self): output = [] for child...
(bot, 'chat') def handle(this, username, message, *args): if (username == bot.username): return if message.startswith('can see'): try: (x, y, z) = map((lambda v: int(v)), message.split('see')[1].replace(',', ' ').split()) except Exception: bot.chat('Bad syntax') ...
.standalone def main(): mayavi.new_scene() r = VTKXMLFileReader() filename = join(mayavi2.get_data_dir(dirname(abspath(__file__))), 'fire_ug.vtu') r.initialize(filename) mayavi.add_source(r) r.point_scalars_name = 'u' o = Outline() mayavi.add_module(o) c = Contour() mayavi.add_fi...
class TermOrder(SimplificationRule): def apply(self, operation: Operation) -> list[tuple[(Expression, Expression)]]: if (operation.operation not in COMMUTATIVE_OPERATIONS): return [] if (not isinstance(operation, BinaryOperation)): raise TypeError(f'Expected BinaryOperation, ...
class Principal(object): def __init__(self, value=None, default_realm=None, type=None): self.type = constants.PrincipalNameType.NT_UNKNOWN self.components = [] self.realm = None if (value is None): return try: if isinstance(value, unicode): ...
def convert_old_fl_trainer_config_to_new(trainer): if ('synctrainer' == trainer['type'].lower()): trainer['_base_'] = 'base_sync_trainer' elif ('asynctrainer' == trainer['type'].lower()): trainer['_base_'] = 'base_async_trainer' elif ('privatesynctrainer' == trainer['type'].lower()): ...
(Output('truncate-hrv-status', 'children'), [Input('truncate-hrv-button', 'n_clicks'), Input('recovery-metric-dropdown-input-submit', 'n_clicks')], [State('truncate-date', 'value')]) def reset_hrv_plan(n_clicks, metric_n_clicks, hrv_date): ctx = dash.callback_context if ctx.triggered: latest = ctx.trigg...
def toolkit_object(name, raise_exceptions=False): global _toolkit if (_toolkit is None): toolkit() obj = _toolkit(name) if (raise_exceptions and (obj.__name__ == 'Unimplemented')): raise RuntimeError("Can't import {} for backend {}".format(repr(name), _toolkit.toolkit)) return obj
def get_talent_data() -> dict[(int, list[dict[(str, int)]])]: total_cats = next_int(4) talents: dict[(int, list[dict[(str, int)]])] = {} for _ in range(total_cats): cat_id = next_int(4) cat_data: list[dict[(str, int)]] = [] number_of_talents = next_int(4) for _ in range(numbe...
def __calculate_track_length(current_track, next_track): (_, _, begin_minute, begin_second, begin_frame) = current_track (_, _, end_minute, end_second, end_frame) = next_track length_minutes = (end_minute - begin_minute) length_seconds = (end_second - begin_second) length_frames = (end_frame - begin...
def module_available(calculator): try: import_name = IMPORT_DICT[calculator] except KeyError: return False try: _ = importlib.import_module(import_name) available = True except (ModuleNotFoundError, ImportError): available = False return available
class PLSFileParser(object): NOT_SET = type('NotSetType', (object,), {}) parser_class = (configparser.SafeConfigParser if hasattr(configparser, 'SafeConfigParser') else configparser.ConfigParser) def __init__(self, path): with warnings.catch_warnings(): warnings.filterwarnings('ignore', ...
class OptionPlotoptionsErrorbarLabel(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): s...
class Platform(GowinPlatform): def __init__(self): GowinPlatform.__init__(self, 'GW1N-LV1QN48C6/I5', _io, [], toolchain='gowin', devicename='GW1N-1') self.toolchain.options['use_done_as_gpio'] = 1 self.toolchain.options['use_reconfign_as_gpio'] = 1 def create_programmer(self): re...
class OptionSeriesScatterSonificationTracksMappingPitch(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): self._con...
class AsyncLogFilter(AsyncFilter): data_filter_set = None data_filter_set_regex = None data_filter_set_function = None log_entry_formatter = None filter_params: FilterParams = None builder: AsyncEventFilterBuilder = None def __init__(self, *args: Any, **kwargs: Any) -> None: self.log...
def test_create_client_and_secret(db, config): (new_client, secret) = ClientDetail.create_client_and_secret(db, config.security.oauth_client_id_length_bytes, config.security.oauth_client_secret_length_bytes) assert (new_client.hashed_secret is not None) assert (hash_with_salt(secret.encode(config.security.e...