code
stringlengths
281
23.7M
('model') def check_no_references(progress_controller=None): if (progress_controller is None): progress_controller = ProgressControllerBase() if len(pm.listReferences()): progress_controller.complete() raise PublishError('There should be no <b>References</b> in a <b>Model</b> scene.') ...
def fix_copr(args, opts, copr_full_name): log.info('Going to fix %s', copr_full_name) (owner, coprname) = tuple(copr_full_name.split('/')) copr_path = os.path.abspath(os.path.join(opts.destdir, owner, coprname)) if (not os.path.isdir(copr_path)): log.info('Ignoring %s. Directory does not exist.'...
class TestBinaryJSONField(FieldValues): valid_inputs = [(b'{"a": 1, "3": null, "b": ["some", "list", true, 1.23]}', {'a': 1, 'b': ['some', 'list', True, 1.23], '3': None})] invalid_inputs = [('{"a": "unterminated string}', ['Value must be valid JSON.'])] outputs = [(['some', 'list', True, 1.23], b'["some", ...
class OptionSeriesAreaSonificationContexttracksMappingGapbetweennotes(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 OptionSeriesPictorialSonificationTracksMappingPlaydelay(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...
def eta2(x, t, w0): b11 = ((1.0 / 32.0) * ((((3.0 * (w0 ** (- 8))) + (6.0 * (w0 ** (- 4)))) - 5.0) + (2.0 * (w0 ** 4)))) b13 = ((3.0 / 128.0) * (((((9.0 * (w0 ** (- 8))) + (27.0 * (w0 ** (- 4)))) - 15.0) + (w0 ** 4)) + (2 * (w0 ** 8)))) b31 = ((1.0 / 128.0) * (((3.0 * (w0 ** (- 8))) + (18.0 * (w0 ** (- 4)))...
def fetch_production(zone_key: str='CA-ON', session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> list: (dt, xml) = _fetch_ieso_xml(target_datetime, session, logger, PRODUCTION_URL) if (not xml): return [] generators = xml.find((XML_NS_TEXT +...
class ColumnMissingValuesMetric(Metric[ColumnMissingValuesMetricResult]): DEFAULT_MISSING_VALUES: ClassVar = ['', np.inf, (- np.inf), None] missing_values: frozenset column_name: str def __init__(self, column_name: str, missing_values: Optional[list]=None, replace: bool=True, options: AnyOptions=None) -...
class TimeBars(Op): __slots__ = ('_timer', 'bars') __doc__ = Tickfilter.timebars.__doc__ bars: BarList def __init__(self, timer, source=None): Op.__init__(self, source) self._timer = timer self._timer.connect(self._on_timer, None, self._on_timer_done) self.bars = BarList(...
class InputFile(): def __init__(self, file) -> None: (self._file, self.file_name) = self._resolve_file(file) def _resolve_file(self, file): if isinstance(file, str): _file = open(file, 'rb') return (_file, os.path.basename(_file.name)) elif isinstance(file, IOBase...
class Splitter(): def __init__(self, context: Context): self._context = context def handle_split(self, splittable: Splittable): previous_lasts = self._context.tree.find_marked(splittable.mark_last()) if (len(previous_lasts) == 0): return previous_last = previous_lasts...
class RevisionIdFilter(FilterBase): def __init__(self, revision_hash_list): super(RevisionIdFilter, self).__init__() self.unwanted_hg_hashes = {h.encode('ascii', 'strict') for h in revision_hash_list} def should_drop_commit(self, commit_data): return (commit_data['hg_hash'] in self.unwan...
class CreateRevisionTest(TestModelMixin, TestBase): def testCreateRevision(self): with reversion.create_revision(): obj = TestModel.objects.create() self.assertSingleRevision((obj,)) def testCreateRevisionNested(self): with reversion.create_revision(): with revers...
def generate_repo_id_and_name_ext(dependent, url, dep_idx): repo_id = 'coprdep:{0}'.format(generate_repo_name(url)) name = 'Copr {0}/{1}/{2} external runtime dependency #{3} - {4}'.format(app.config['PUBLIC_COPR_HOSTNAME'].split(':')[0], dependent.owner_name, dependent.name, dep_idx, generate_repo_name(url)) ...
def size(value: Any, unit: str='%', toStr: bool=False): if (value is False): return (None, '') if isinstance(value, tuple): if toStr: return '{}{}'.format(value[0], value[1]) return value elif (value == 'auto'): return (value, '') elif isinstance(value, str): ...
class OptionPlotoptionsPackedbubbleSonificationContexttracksMappingLowpass(Options): def frequency(self) -> 'OptionPlotoptionsPackedbubbleSonificationContexttracksMappingLowpassFrequency': return self._config_sub_data('frequency', OptionPlotoptionsPackedbubbleSonificationContexttracksMappingLowpassFrequency...
def iter_generate_delft_training_data_lines_for_document(tei_file: str, raw_file: Optional[str], training_tei_parser: TrainingTeiParser, data_generator: ModelDataGenerator) -> Iterable[str]: with auto_download_input_file(tei_file, auto_decompress=True) as local_tei_file: tei_root = etree.parse(local_tei_fil...
def lazy_import(): from fastly.model.included_with_waf_rule_revision import IncludedWithWafRuleRevision from fastly.model.waf_rule_revision_response_data import WafRuleRevisionResponseData globals()['IncludedWithWafRuleRevision'] = IncludedWithWafRuleRevision globals()['WafRuleRevisionResponseData'] = W...
class Configuration(JSONSerializable, ABC): __slots__ = ('_key_order',) def __init__(self) -> None: self._key_order: List[str] = [] def from_json(cls, obj: Dict) -> 'Configuration': def ordered_json(self) -> OrderedDict: data = self.json result = OrderedDict() seen_keys =...
def test_dependencies_from_to_json(): version_str = '==0.1.0' git_url = ' branch = 'some-branch' dep1 = Dependency('package_1', version_str, DEFAULT_PYPI_INDEX_URL, git_url, branch) dep2 = Dependency('package_2', version_str) expected_obj = {'package_1': dep1, 'package_2': dep2} expected_obj...
class CustomSessionInterface(SessionInterface): EXPIRES_MINUTES = (48 * 60) session_class = CustomSession def __init__(self, cache, prefix='session$'): self.cache = cache self.prefix = prefix def open_session(self, app, request): session_id = request.cookies.get(app.config['SESSI...
class WatsonCredentialsDialog(Gtk.Dialog): def __init__(self, parent): Gtk.Dialog.__init__(self, 'Enter Credentials', parent, 0, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK, Gtk.ResponseType.OK)) self.set_default_size(150, 100) username_field = Gtk.Entry() username_field...
class RDKitMoleculeSetup(MoleculeSetup): def from_mol(cls, mol, keep_chorded_rings=False, keep_equivalent_rings=False, assign_charges=True, conformer_id=(- 1)): if cls.has_implicit_hydrogens(mol): raise ValueError('RDKit molecule has implicit Hs. Need explicit Hs.') if (mol.GetNumConform...
class ActionDispatcher(BackendDispatcher): task_type = 'action' worker_manager_class = ActionWorkerManager def __init__(self, backend_opts): super().__init__(backend_opts) self.max_workers = backend_opts.actions_max_workers def get_frontend_tasks(self): try: raw_actio...
def test_can_detect_stuck_states(): with pytest.raises(InvalidDefinition, match='All non-final states should have at least one outgoing transition.'): class CampaignMachine(StateMachine, strict_states=True): draft = State(initial=True) producing = State() paused = State()...
class GLUMask(nn.Module): def __init__(self, n_freq, n_bottleneck, pool_size=2, kernel_size=3, dropout_p=0.5, mag_spec=True, log_spec=True, n_sublayers=1): super().__init__() self.mag_spec = mag_spec self.log_spec = log_spec if mag_spec: n_inputs = n_freq else: ...
def test_creosote_project_success(venv_manager: VenvManager, capsys: CaptureFixture) -> None: (venv_path, site_packages_path) = venv_manager.create_venv() for dependency_name in ['dotty-dict', 'loguru', 'pip-requirements-parser', 'toml']: venv_manager.create_record(site_packages_path=site_packages_path,...
class IterableList(): def __init__(self, items: List[Any]): self.items = items def __iter__(self): return self.Iterator(self.items) class Iterator(): def __init__(self, items: List[Any]): self.iter = iter(items) def __iter__(self): return self ...
class OptionPlotoptionsNetworkgraphSonificationContexttracksActivewhen(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, num...
class OptionSeriesColumnSonificationTracksMapping(Options): def frequency(self) -> 'OptionSeriesColumnSonificationTracksMappingFrequency': return self._config_sub_data('frequency', OptionSeriesColumnSonificationTracksMappingFrequency) def gapBetweenNotes(self) -> 'OptionSeriesColumnSonificationTracksMap...
def align(sequences): lengths = [] indices = [] offset = 0 for seq in sequences: for token_length in seq: lengths.append(token_length) indices.extend(((i + offset) for i in range(token_length))) offset += token_length return Ragged(numpy.array(indices, dty...
def get_func_args(func): if PY2: argspec = inspect.getargspec(func) if inspect.ismethod(func): return argspec.args[1:] return argspec.args else: sig = inspect.signature(func) return [name for (name, param) in sig.parameters.items() if ((param.kind == inspect.P...
def test_auth(server): url = str(server.url) runner = CliRunner() result = runner.invoke( [url, '-v', '--auth', 'username', 'password']) print(result.output) assert (result.exit_code == 0) assert (remove_date_header(splitlines(result.output)) == ["* Connecting to '127.0.0.1'", "* Connected to '1...
class OnScrollEvent(ControlEvent): def __init__(self, t, p, minse, maxse, vd, sd=None, dir=None, os=None, v=None) -> None: self.event_type: str = t self.pixels: float = p self.min_scroll_extent: float = minse self.max_scroll_extent: float = maxse self.viewport_dimension: floa...
def attach_image(msg, url, file_path, selector, dimensions='1024x1024'): if ('selectedTab=map' in url): wait = 8000 dimensions = '1000x600' elif ('selectedTab=chart' in url): wait = 1000 dimensions = '800x600' elif ('selectedTab' in url): wait = 500 dimensions...
def truthy(o: Any) -> Optional[bool]: if isinstance(o, str): if (o.lower() in {'y', 'yes', 't', 'true', '1'}): return True elif (o.lower() in {'n', 'no', 'f', 'false', '0'}): return False else: return None elif (o is None): return None else...
class DOSContractCreateEmptyContractBenchmark(BaseDOSContractBenchmark): def name(self) -> str: return 'DOSContract empty contract deployment' def _setup_benchmark(self, chain: MiningChain) -> None: self.deploy_dos_contract(chain) chain.mine_block() def _apply_transaction(self, chain...
class LedgerApiDialogues(BaseLedgerApiDialogues): def __init__(self, self_address: Address, **kwargs) -> None: def role_from_first_message(message: Message, receiver_address: Address) -> BaseDialogue.Role: return LedgerApiDialogue.Role.AGENT BaseLedgerApiDialogues.__init__(self, self_add...
class TestProcessNextRequests(TestCase): def test_emtpy_request_returns_job_response_error(self): settings = factories.ServerSettingsFactory() server = HandleNextRequestServer(settings=settings) server.transport = SimplePassthroughServerTransport(server.service_name) server.transport...
def template_injection_url(uri, scanid): result = subprocess.check_output(['python3', './tplmap/tplmap.py', '-u', uri], text=True) output = str(result) if ('not injectable' in output.lower()): print('Endpoint is not vulnerable') else: newoutput = result.split('\n') for line in ne...
class ChooseWalletPage(QWizardPage): HELP_CONTEXT = HelpContext('choose-wallet') _force_completed = False _list_thread_context: Optional[ListPopulationContext] = None _list_thread: Optional[threading.Thread] = None _commit_pressed = False def __init__(self, parent: WalletWizard) -> None: ...
class StatsDictTest(TestCaseBase): def test_add(self) -> None: n = 10 a = np.random.rand(n) b = np.random.randn(n) d = StatsDict() for (x, y) in zip(a.tolist(), b.tolist()): d.add('a', x) d.add('b', y) self.assertEqual(d['a'].count(), n) ...
class DecisionTree(elmdptt.TaskModelInitialization): criterion = luigi.Parameter() max_depth = luigi.Parameter() min_samples_leaf = luigi.Parameter random_state = luigi.Parameter() max_leaf_nodes = luigi.Parameter() def actual_task_code(self): model = tree.DecisionTreeClassifier(criterio...
def test_full_backfill_if_metric_not_updated_for_a_long_time(dbt_project: DbtProject, test_id: str): date_gap_size = 15 utc_today = datetime.utcnow().date() data_dates = generate_dates(base_date=(utc_today - timedelta(1))) data = [{TIMESTAMP_COLUMN: cur_date.strftime(DATE_FORMAT)} for cur_date in data_d...
class UniqueForMonthTests(TestCase): def setUp(self): self.instance = UniqueForMonthModel.objects.create(slug='existing', published='2017-01-01') def test_not_unique_for_month(self): data = {'slug': 'existing', 'published': '2017-01-01'} serializer = UniqueForMonthSerializer(data=data) ...
class TestOFPActionDecMplsTtl(unittest.TestCase): type_ = ofproto.OFPAT_DEC_MPLS_TTL len_ = ofproto.OFP_ACTION_MPLS_TTL_SIZE fmt = ofproto.OFP_ACTION_HEADER_PACK_STR buf = pack(fmt, type_, len_) c = OFPActionDecMplsTtl() def test_parser(self): res = self.c.parser(self.buf, 0) eq_...
class OptionPlotoptionsDumbbellSonificationDefaultspeechoptionsMappingVolume(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 bsn_set_switch_pipeline_request(bsn_header): version = 6 type = 4 experimenter = 6035143 subtype = 53 def __init__(self, xid=None, pipeline=None): if (xid != None): self.xid = xid else: self.xid = None if (pipeline != None): self.pipe...
class DeadPathElimination(PipelineStage): name = 'dead-path-elimination' def __init__(self): self._logic_converter: BaseConverter = Z3Converter() self._timeout: Optional[int] = None def run(self, task: DecompilerTask) -> None: self._timeout = task.options.getint(f'{self.name}.timeout...
def ovlp3d_33(ax, da, A, bx, db, B): result = numpy.zeros((10, 10), dtype=float) x0 = ((ax + bx) ** (- 1.0)) x1 = (x0 * ((ax * A[0]) + (bx * B[0]))) x2 = (- x1) x3 = (x2 + B[0]) x4 = (x0 * ((((- 2.0) * x1) + A[0]) + B[0])) x5 = (x2 + A[0]) x6 = (x3 * x5) x7 = (x0 + (2.0 * x6)) x8...
def test_upload(monkeypatch, set_api_key): responses.add(responses.GET, f'{Env.current.web_api_endpoint}/tidy3d/tasks/3eb06d16-208b-487b-864b-e9b1d3e010a7/detail', json={'data': {'taskId': '3eb06d16-208b-487b-864b-e9b1d3e010a7', 'createdAt': '2022-01-01T00:00:00.000Z'}}, status=200) def mock_download(*args, **k...
class SignatureDuplicationTandem(Signature): def __init__(self, contig, start, end, copies, fully_covered, signature, read): self.contig = contig assert (end >= start) self.start = start self.end = end self.copies = copies self.fully_covered = fully_covered se...
class VarImpl(object): def __init__(self, local_scope): self._local_scope = local_scope def Lookup(self, var_name): if (var_name in self._local_scope.get('vars', {})): return self._local_scope['vars'][var_name] if (var_name == 'host_os'): return 'linux' if...
def repeat(interval, callback, persistent=True, idstring='', stop=False, store_key=None, *args, **kwargs): global _TICKER_HANDLER if (_TICKER_HANDLER is None): from evennia.scripts.tickerhandler import TICKER_HANDLER as _TICKER_HANDLER if stop: _TICKER_HANDLER.remove(interval=interval, callb...
class PlotFrame(DemoFrame): def _create_component(self): numpoints = 50 low = (- 5) high = 15.0 x = arange(low, high, ((high - low) / numpoints)) container = OverlayPlotContainer(bgcolor='lightgray') common_index = None index_range = None value_range =...
class LZString(): def __init__(self): self.vm = None def init(self, html, url): if self.vm: return cryptojs = re.search('src="([^"]+?/crypt_\\w+?\\.js)"', html).group(1) cryptojs = grabhtml(urljoin(url, cryptojs), referer=url) self.vm = VM(f'window = self; {cr...
(firedrake.DirichletBC) def coarsen_bc(bc, self, coefficient_mapping=None): V = self(bc.function_space(), self, coefficient_mapping=coefficient_mapping) val = self(bc.function_arg, self, coefficient_mapping=coefficient_mapping) subdomain = bc.sub_domain return type(bc)(V, val, subdomain)
class RegistrationSessionRepository(BaseRepository[RegistrationSession], UUIDRepositoryMixin[RegistrationSession], ExpiresAtMixin[RegistrationSession]): model = RegistrationSession async def get_by_token(self, token: str, *, fresh: bool=True) -> (RegistrationSession | None): statement = select(Registrat...
def fetch_exchange(zone_key1: ZoneKey, zone_key2: ZoneKey, session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> list[dict]: if target_datetime: raise NotImplementedError('This parser is not yet able to parse past dates') sorted_zone_keys = ZoneK...
def compare_and_update_pips(pips, new_pips): assert (pips.keys() == new_pips.keys()), repr((pips.keys(), new_pips.keys())) for name in pips: if ((pips[name]['src_wire'] is not None) and (new_pips[name]['src_wire'] is not None)): assert (pips[name]['src_wire'] == new_pips[name]['src_wire']), ...
class _Uninitialized(object): def __new__(cls): if (Uninitialized is not None): return Uninitialized else: self = object.__new__(cls) return self def __repr__(self): return '<uninitialized>' def __reduce_ex__(self, protocol): return (_Unini...
def get_linked_addon_note(anki_nid: int) -> Optional[Tuple[(SiacNote, int)]]: c = _get_connection() res = c.execute(f'select distinct notes.*, notes_pdf_page.page from notes join notes_pdf_page on notes.id = notes_pdf_page.siac_nid where notes_pdf_page.nid = {anki_nid}').fetchall() c.close() if ((res is...
def gen_sites(): db = Database(util.get_db_root(), util.get_part()) grid = db.grid() for tile_name in sorted(grid.tiles()): loc = grid.loc_of_tilename(tile_name) gridinfo = grid.gridinfo_at_loc(loc) if (gridinfo.tile_type in ['CLBLL_L', 'CLBLL_R', 'CLBLM_L', 'CLBLM_R']): ...
class UiReadout(object): def __init__(self, hashQueue, monitorQueue): self.log = logging.getLogger('Main.UI') self.hashQueue = hashQueue self.processingHashQueue = monitorQueue self.stopOnEmpty = False self.stopped = False def run(self): commits = 0 pbar =...
def laguerre_recurrence_coefficients(a, order): nn = (int(order) + 1) ab = np.zeros((nn, 2)) if (a <= (- 1)): raise ValueError('First input must be >= -1!') nu_value = (a + 1) mu_value = gamma((a + 1)) ab[(0, 0)] = nu_value ab[(0, 1)] = mu_value if (nn == 1): return ab ...
def _guess_extension(content_type): return {'application/javascript': '.js', 'application/msword': '.doc', 'application/octet-stream': '.bin', 'application/oda': '.oda', 'application/pdf': '.pdf', 'application/pkcs7-mime': '.p7c', 'application/postscript': '.ps', 'application/vnd.apple.mpegurl': '.m3u', 'applicatio...
def extractInfinityTranslations(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())): return None if ('ETC' in item['tags']): return buildReleaseMessageWithType(item, 'Emperor of The Cosmos'...
.django_db def test_award_update_contract_txn_with_list(): awards = [baker.make('search.AwardSearch', award_id=i, total_obligation=0, generated_unique_award_id=f'AWARD_{i}') for i in range(5)] baker.make('search.TransactionSearch', transaction_id=10, award=awards[0], is_fpds=True, base_and_all_options_value=100...
class TestGetLayoutGraphicWithSimilarCoordinates(): def test_should_return_the_best_matching_graphic(self): page_graphics = [LayoutGraphic(coordinates=LayoutPageCoordinates(x=10, y=10, width=200, height=100)), LayoutGraphic(coordinates=LayoutPageCoordinates(x=10, y=10, width=100, height=100)), LayoutGraphic...
class String(Value): unescapable = re.compile('^[^\\\\():<>"*{} \\t\\r\\n]+$') escapes = {'\t': '\\t', '\r': '\\r', '"': '\\"'} def _render(self): if (self.unescapable.match(self.value) is not None): return str(self.value) regex = '[{}]'.format(''.join((re.escape(s) for s in sort...
class ExamplePlotApp(HasTraits): plot = Instance(Plot) def _plot_default(self): index = numpy.arange(1.0, 10.0, 0.01) series1 = ((100.0 + index) / ((100.0 - (20 * (index ** 2))) + (5.0 * (index ** 4)))) series2 = ((100.0 + index) / ((100.0 - (20 * (index ** 2))) + (5.0 * (index ** 3)))) ...
_deserializable class CacheInitConfig(BaseConfig): def __init__(self, similarity_threshold: Optional[float]=0.8, auto_flush: Optional[int]=20): if ((similarity_threshold < 0) or (similarity_threshold > 1)): raise ValueError(f'similarity_threshold {similarity_threshold} should be between 0 and 1'...
def _start(): global patch, name, path, monitor global delay, prefix, input_name, input_variable delay = patch.getfloat('general', 'delay') prefix = patch.getstring('output', 'prefix') (input_name, input_variable) = list(zip(*patch.config.items('input'))) for (name, variable) in zip(input_name, ...
class MyETW(etw.ETW): def __init__(self, event_callback): providers = [etw.ProviderInfo('Some Provider', etw.GUID('{-1111-1111-1111-}'))] super().__init__(providers=providers, event_callback=event_callback) def start(self): self.do_capture_setup() super().start() def stop(sel...
class BuildKubernetesSchema(StrictSchema): class_name = ma.fields.String(required=True) _schema def check_valid_class(self, data): ALLOWED_CLASS = ['airflow.contrib.kubernetes.volume.Volume', 'airflow.contrib.kubernetes.volume_mount.VolumeMount', 'airflow.contrib.kubernetes.secret.Secret', 'airflow....
def test_that_index_file_is_read(tmpdir): with tmpdir.as_cwd(): with open('config.ert', 'w', encoding='utf-8') as fh: fh.writelines(dedent('\n JOBNAME my_name%d\n NUM_REALIZATIONS 10\n OBS_CONFIG observations\n GEN_DATA ...
_lock(timeout=300, key_args=(2,), wait_for_release=True, base_name='vm_status_changed') def _vm_status_check(task_id, node_uuid, uuid, state, state_cache=None, vm=None, change_time=None, force_change=False, **kwargs): if (state_cache is None): try: vm = Vm.objects.select_related('slavevm').get(u...
class TestFilteredTraitObserverEqualHash(unittest.TestCase): def test_not_equal_filter(self): observer1 = FilteredTraitObserver(notify=True, filter=DummyFilter(return_value=True)) observer2 = FilteredTraitObserver(notify=True, filter=DummyFilter(return_value=False)) self.assertNotEqual(obser...
def test_protobuf_envelope_serializer(): serializer = ProtobufEnvelopeSerializer() envelope_context = EnvelopeContext(connection_id=None, uri=URI('/uri')) expected_envelope = Envelope(to='to', sender='sender', protocol_specification_id=PublicId('author', 'name', '0.1.0'), message=b'message', context=envelop...
def GetMatrix(pos, quat) -> np.ndarray: q = quat.copy() n = np.dot(q, q) if (n < np.finfo(q.dtype).eps): return np.identity(4) q = (q * np.sqrt((2.0 / n))) q = np.outer(q, q) matrix = np.array([[((1.0 - q[(1, 1)]) - q[(2, 2)]), (- (q[(2, 3)] - q[(1, 0)])), (q[(1, 3)] + q[(2, 0)]), pos[0]...
def test_ref_lp_from_decorator_with_named_outputs(): _launch_plan(project='project', domain='domain', name='name', version='version') def ref_lp1(p1: str, p2: str) -> typing.NamedTuple('RefLPOutput', o1=int, o2=str): ... assert (ref_lp1.python_interface.outputs == {'o1': int, 'o2': str})
_required _required _required(UserAdminPermission) _required _POST def dc_user_modal_form(request): qs = request.GET.copy() if (request.POST['action'] == 'update'): user = get_edited_user(request, request.POST['adm-username']) else: user = None form = AdminUserModalForm(request, user, re...
class MinHashLSHEnsemble(object): def __init__(self, threshold: float=0.9, num_perm: int=128, num_part: int=16, m: int=8, weights: Tuple[(float, float)]=(0.5, 0.5), storage_config: Optional[Dict]=None, prepickle: Optional[bool]=None) -> None: if ((threshold > 1.0) or (threshold < 0.0)): raise Va...
def evaluate(base, string): colors = [] try: color = string.strip() second = None method = None (first, method, more) = parse_color(base, color) if (first and (more is not None)): if (more is False): first = None else: ...
def async_mock_offchain_lookup_request_response(monkeypatch: 'MonkeyPatch', Literal[('GET', 'POST')]='GET', mocked_request_url: str=None, mocked_status_code: int=200, mocked_json_data: str='0x', json_data_field: str='data', sender: str=None, calldata: str=None) -> None: class AsyncMockedResponse(): status ...
def expand_braces(patterns: AnyStr, flags: int, limit: int) -> Iterable[AnyStr]: if (flags & BRACE): for p in ([patterns] if isinstance(patterns, (str, bytes)) else patterns): try: (yield from bracex.iexpand(p, keep_escapes=True, limit=limit)) except bracex.ExpansionL...
class TestHtml5NthOfSelectors(util.PluginTestCase): def setup_fs(self): template = self.dedent('\n <!DOCTYPE html>\n <html>\n <head>\n <meta content="text/html; charset=UTF-8">\n </head>\n <body>\n <p>aaaa</p>\n <p>bb...
def test_contract_init_with_w3_function_name(w3, function_name_tester_contract_abi, function_name_tester_contract): contract_factory = w3.eth.contract(abi=function_name_tester_contract_abi) contract = contract_factory(function_name_tester_contract.address) result = contract.functions.w3().call() assert ...
def __create_marker_context_menu(): items = [] def on_jumpto_item_activate(widget, name, parent, context): position = context['current-marker'].props.position player.PLAYER.set_progress(position) def on_remove_item_activate(widget, name, parent, context): providers.unregister('playba...
class LanguageErrorMessage(): LANGUAGE_REQUIRED = (lambda input_lang: f"This provider doesn't auto-detect languages, please provide a valid {input_lang}") LANGUAGE_NOT_SUPPORTED = (lambda lang, input_lang: f'Provider does not support selected {input_lang}: `{lang}`') LANGUAGE_GENERIQUE_REQUESTED = (lambda l...
class ReceiverStreamsCombiner(): def __init__(self, output_batch_queue: OutputBatchQueue): self.output_batch_queue = output_batch_queue self.tasks: Dict[(BaseReceiver, Awaitable[Tuple[(BaseReceiver, dm.ResponseBatch)]])] = {} self.running = True self.receivers_to_delete: List[BaseRec...
.parametrize('num_modes, log_level', [(101, 'WARNING'), (100, None)]) def test_monitor_num_modes(log_capture, num_modes, log_level): monitor = td.ModeMonitor(size=(td.inf, 0, td.inf), freqs=np.linspace(.0, .0, 100), name='test', mode_spec=td.ModeSpec(num_modes=num_modes)) assert_log_level(log_capture, log_level...
_required _passes_test(is_organizer, 'index') def change_activity_status(request, event_slug, activity_id, status, justification=None): event = get_object_or_404(Event, event_slug=event_slug) activity = get_object_or_404(Activity, id=activity_id) activity.status = status activity.start_date = None a...
class AmazonTranslationApi(TranslationInterface): def translation__language_detection(self, text) -> ResponseType[LanguageDetectionDataClass]: response = self.clients['text'].detect_dominant_language(Text=text) items: Sequence[InfosLanguageDetectionDataClass] = [] for lang in response['Langu...
def test_link_in_headers(response_with_header_link): config = LinkPaginationConfiguration(source='headers', rel='next') request_params: SaaSRequestParams = SaaSRequestParams(method=HTTPMethod.GET, path='/customers', query_params={'page': 'abc'}) paginator = LinkPaginationStrategy(config) next_request: O...
def test_reference(): definitions = typesystem.Definitions() album = typesystem.Schema(fields={'title': typesystem.String(max_length=100), 'release_date': typesystem.Date(), 'artist': typesystem.Reference('Artist', definitions=definitions)}) artist = typesystem.Schema(fields={'name': typesystem.String(max_l...
class TicketingManager(): def calculate_update_amount(order): discount = None if order.discount_code_id: discount = order.discount_code amount = 0 total_discount = 0 fees = TicketFees.query.filter_by(currency=order.event.payment_currency).first() for order...
def _parse_expand_colnames(adapter, fieldlist): (rv, tables) = ([], {}) for field in fieldlist: if (not isinstance(field, Field)): rv.append(None) continue table = field.table (tablename, fieldname) = (table._tablename, field.name) ft = field.type ...
class TestModelingModelEMAHook(unittest.TestCase): def test_ema_hook(self): runner = default_runner.Detectron2GoRunner() cfg = runner.get_default_cfg() cfg.MODEL.DEVICE = 'cpu' cfg.MODEL_EMA.ENABLED = True cfg.MODEL_EMA.DECAY = 0.0 cfg.MODEL_EMA.DECAY_WARM_UP_FACTOR =...
class port_mod(message): version = 3 type = 16 def __init__(self, xid=None, port_no=None, hw_addr=None, config=None, mask=None, advertise=None): if (xid != None): self.xid = xid else: self.xid = None if (port_no != None): self.port_no = port_no ...