code
stringlengths
281
23.7M
def load_corpus(name, download=True): path = corpora[name] if (not os.path.exists(path)): raise ValueError("'{}' dataset has not been downloaded, use the download.py module to fetch datasets".format(name)) categories = [cat for cat in os.listdir(path) if os.path.isdir(os.path.join(path, cat))] f...
class nicira_controller_role_reply(nicira_header): version = 1 type = 4 experimenter = 8992 subtype = 11 def __init__(self, xid=None, role=None): if (xid != None): self.xid = xid else: self.xid = None if (role != None): self.role = role ...
def does_file_need_fix(filepath: str) -> bool: if (not re.search('\\.pyi?$', filepath)): return False with open(filepath, mode='r') as f: first_license_line = None for line in f: if (line == license_header_lines[0]): first_license_line = line b...
def extractDefiringCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type) in tagmap...
class TestConsentVerify(): (scope='function') def verification_code(self) -> str: return 'abcd' def test_consent_verify_no_consent_request_id(self, api_client): data = {'code': '12345'} response = api_client.post(f"{V1_URL_PREFIX}{CONSENT_REQUEST_VERIFY.format(consent_request_id='non...
class TestDeletion(CustomTestCase): uri = '/sleep' def create_app(): app.config['TESTING'] = True return app def test_delete__204(self): r1 = self.client.post(self.uri, json={'args': ['10'], 'force_unique_key': True}) r1_json = r1.get_json() self.assertStatus(r1, 202)...
def getTaskValueIndex(taskname, valuename): tid = (- 1) vid = (- 1) global Tasks for x in range(0, len(Tasks)): if (Tasks[x] and (type(Tasks[x]) is not bool)): try: if Tasks[x].enabled: if (Tasks[x].gettaskname() == taskname): ...
class TestCombineData(unittest.TestCase): def setUp(self): self.species1 = u'Probe_Set_ID\tPublic_ID\n1053_at\tM87338\n117_at\tX51757\n121_at\tX69699\n1255_g_at\tL36861\n' self.species2 = u'Probe_Set_ID\tPublic_ID\n1417503_at\tNM_020022\n1457638_x_at\tAV039064\n1457669_x_at\tAV096765\n1418208_at\tNM...
class PageSettings(AbstractObject): def __init__(self, api=None): super(PageSettings, self).__init__() self._isPageSettings = True self._api = api class Field(AbstractObject.Field): setting = 'setting' value = 'value' _field_types = {'setting': 'string', 'value': 'Obj...
class OptionSeriesBoxplotSonificationContexttracksMappingTremoloDepth(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 ExampleDirLanguages(BaseExampleDir): def __init__(self): BaseExampleDir.__init__(self) self.add_file('hello', 'Hello!') self.add_file('goodbye', 'Goodbye!') self.add_file('spanish/hola', 'Hello!') self.add_file('spanish/adios', 'Goodbye!') self.add_file('welsh/n...
def test_sequential_cooling(): calc_kwargs = {'scale': 0.01} geom = AnaPot().get_saddles(i=0, geom_kwargs={'coord_type': 'mwcartesian'}, calc_kwargs=calc_kwargs) calc = geom.calculator def calc_getter(): return AnaPot(**calc_kwargs) P = 20 T = 400 Ts = np.linspace(T, 100, num=10) ...
class WMAP5BAOSNCosmology(FRWCosmology): _params = ('t0', 'sigma8', 'omegaB', 'omegaC', 'ns') t0 = 13.73 t0_err = 0.12 sigma8 = 0.817 sigma8_err = 0.026 ns = 0.96 ns_err = (0.013, 0.014) H0 = 70.1 H0_err = 1.3 omegaB = 0.046 omegaB_err = 0.0015 omegaC = 0.233 omegaC_e...
def test_forwarded_quote_escaping(asgi): req = create_req(asgi, host='suchproxy02.suchtesting.com', path='/languages', root_path='doge', headers={'Forwarded': 'for="1\\.2\\.3\\.4";some="extra,\\"info\\""'}) assert (req.forwarded[0].host is None) assert (req.forwarded[0].src == '1.2.3.4')
class TestANSIString(TestCase): def setUp(self): self.example_raw = '|relectric |cboogaloo|n' self.example_ansi = AN(self.example_raw) self.example_str = 'electric boogaloo' self.example_output = '\x1b[1m\x1b[31melectric \x1b[1m\x1b[36mboogaloo\x1b[0m' def test_length(self): ...
class RightToolbar(Toolbar): ui = 'ui/coverart_rightsidebar.ui' name = 'right' def hide(self): if self.builder.get_visible(): self.builder.hide() self.plugin.shell.remove_widget(self.builder, RB.ShellUILocation.RIGHT_SIDEBAR) def show(self): self.plugin.shell.add_...
class ManualSchema(ViewInspector): def __init__(self, fields, description='', encoding=None): super().__init__() if (coreapi is not None): warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) assert all((isinstance(f, coreap...
_tag('django_social_share/templatetags/post_to_whatsapp.html', takes_context=True) def post_to_whatsapp(context, obj_or_url=None, link_text='', link_class=''): context = post_to_whatsapp_url(context, obj_or_url) context['link_class'] = link_class context['link_text'] = (link_text or 'Post to WhatsApp') ...
def test_extract_seed_nodes() -> None: t = generate_graph_resources(3) field(t, 'dr_1', 'ds_1', 'f1').references.append((FieldAddress('dr_2', 'ds_2', 'f1'), None)) field(t, 'dr_1', 'ds_1', 'f1').references.append((FieldAddress('dr_3', 'ds_3', 'f1'), None)) field(t, 'dr_1', 'ds_1', 'f1').identity = 'x' ...
class EmulateEfuseController(EmulateEfuseControllerBase): CHIP_NAME = 'ESP32-S3' mem = None debug = False def __init__(self, efuse_file=None, debug=False): self.Blocks = EfuseDefineBlocks self.Fields = EfuseDefineFields() self.REGS = EfuseDefineRegisters super(EmulateEfus...
class NeverMatch(Field): errors = {'never': 'This never validates.'} def __init__(self, **kwargs: typing.Any) -> None: assert ('allow_null' not in kwargs) super().__init__(**kwargs) def validate(self, value: typing.Any) -> typing.Any: raise self.validation_error('never')
class SoftThreadPool(): def __init__(self, nthreads=4): self._nthreads = nthreads self._queue = [] self._condition = threading.Condition() self._active = False self._lock = threading.RLock() self._error = None def __enter__(self): return self def __exi...
class RedisStrategy(Strategy[(models.UP, models.ID)], Generic[(models.UP, models.ID)]): def __init__(self, redis: redis.asyncio.Redis, lifetime_seconds: Optional[int]=None, *, key_prefix: str='fastapi_users_token:'): self.redis = redis self.lifetime_seconds = lifetime_seconds self.key_prefix...
def complete(service, task_token, return_value: object) -> Optional[Exception]: respond = RespondActivityTaskCompletedRequest() respond.task_token = task_token respond.result = json.dumps(return_value) respond.identity = WorkflowService.get_identity() (_, error) = service.respond_activity_task_compl...
def test_des_not_too_slowed_down(): n = 10000 data_u8 = np.zeros((n, 8), dtype='uint8') data_u32 = np.zeros((n, 8), dtype='uint32') key = np.zeros(16, dtype='uint8') t0 = time.process_time() scared.des.encrypt(data_u8, key) pt_u8 = (time.process_time() - t0) t0 = time.process_time() ...
def templated(template_name): def decorator(func): (func) def decorated_function(*args, **kwargs): ctx = func(*args, **kwargs) if (ctx is None): ctx = {} elif (not isinstance(ctx, dict)): return ctx return render_templat...
class TestJobRequestSchema(): () def job(self): return {'control': {'continue_on_error': False}, 'context': {'switches': [1, 2, 3], 'correlation_id': six.u(str(uuid.uuid4()))}, 'actions': [{'action': 'test_action_name', 'body': {'first_name': 'Bob', 'last_name': 'Mueller'}}]} def test_valid_job(self...
class TestActionFileDeleteSnapshots(CuratorTestCase): def test_deletesnapshot(self): self.create_repository() timestamps = [] for i in range(1, 4): self.add_docs(f'my_index{i}') ilo = IndexList(self.client) snap = Snapshot(ilo, repository=self.args['reposi...
() def add_multiple_service_units(parent, data): if ((not parent) or (not data)): return data = json.loads(data) company = (data.get('company') or frappe.defaults.get_defaults().get('company') or frappe.db.get_single_value('Global Defaults', 'default_company')) if ((not data.get('healthcare_serv...
def crack_hash(passwd_entry: bytes, result_entry: dict, format_term: str='') -> bool: with NamedTemporaryFile() as fp: fp.write(passwd_entry) fp.seek(0) john_process = run_docker_container('fact/john:alpine-3.18', command=f'/work/input_file {format_term}', mounts=[Mount('/work/input_file', f...
class OptionSeriesBarSonificationTracks(Options): def activeWhen(self) -> 'OptionSeriesBarSonificationTracksActivewhen': return self._config_sub_data('activeWhen', OptionSeriesBarSonificationTracksActivewhen) def instrument(self): return self._config_get('piano') def instrument(self, text: s...
def get_channel_path(view): params = {} params['ParentId'] = view.get('Id') params['IsMissing'] = False params['ImageTypeLimit'] = 1 params['Fields'] = '{field_filters}' path = get_emby_url('{server}/emby/Users/{userid}/Items', params) url = (((sys.argv[0] + '?url=') + urllib.parse.quote(pat...
(stability='beta') class ModelRequest(): model: str messages: List[_ModelMessageType] temperature: Optional[float] = None max_new_tokens: Optional[int] = None stop: Optional[str] = None stop_token_ids: Optional[List[int]] = None context_len: Optional[int] = None echo: Optional[bool] = Tr...
class ConstantField(): def __init__(self, date, param, proc, shape, number=None): self.date = date self.param = param self.number = number self.proc = proc self.shape = shape self._metadata = dict(valid_datetime=(date if isinstance(date, str) else date.isoformat()), p...
class Member(User): def __init__(self, raw, group): super(Member, self).__init__(raw, group.bot) self._group_user_name = group.user_name def group(self): for _group in self.bot.groups(): if (_group.user_name == self._group_user_name): return _group rai...
class _BaseTwitchCombatCommand(Command): def at_pre_command(self): if ((not self.caller.location) or (not self.caller.location.allow_combat)): self.msg("Can't fight here!") raise InterruptCommand() def parse(self): self.args = args = self.args.strip() (self.lhs, s...
def _freeze_matched_bn(module, name, reg_exps, matched_names, unmatched_names): res = module if (len(list(module.children())) == 0): if isinstance(module, nn.modules.batchnorm._BatchNorm): matched = False for frozen_layers_regex in reg_exps: if re.match(frozen_lay...
class OptionSeriesTreemapStatesInactive(Options): def animation(self) -> 'OptionSeriesTreemapStatesInactiveAnimation': return self._config_sub_data('animation', OptionSeriesTreemapStatesInactiveAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): ...
def test_get_ipv4_os(): endpoint = endpoint_factory('foo') endpoint.endpoint_data = {'tenant': 'foo', 'mac': '00:00:00:00:00:00', 'segment': 'foo', 'port': '1', 'ipv4': '0.0.0.0'} endpoint.metadata = {'ipv4_addresses': {}} ipv4_os = GetData._get_ipv4_os(endpoint) assert (ipv4_os == NO_DATA) endp...
class GS(JsPackage): lib_alias = {'js': 'gridstack', 'css': 'gridstack'} def added(self, js_funcs: types.JS_FUNCS_TYPES, profile: types.PROFILE_TYPE=False): return JsObjects.JsVoid(("%s.on('added', function(event, items){%s})" % (self.varName, JsUtils.jsConvertFncs(js_funcs, toStr=True, profile=profile)...
class OptionPlotoptionsArcdiagramStatesSelect(Options): def animation(self) -> 'OptionPlotoptionsArcdiagramStatesSelectAnimation': return self._config_sub_data('animation', OptionPlotoptionsArcdiagramStatesSelectAnimation) def borderColor(self): return self._config_get('#000000') def borderC...
def test_override(): class _Container(containers.DeclarativeContainer): p11 = providers.Provider() class _OverridingContainer1(containers.DeclarativeContainer): p11 = providers.Provider() class _OverridingContainer2(containers.DeclarativeContainer): p11 = providers.Provider() ...
def test_nan_behaviour_error_fit(df_enc_big_na): encoder = StringSimilarityEncoder(missing_values='raise') with pytest.raises(ValueError) as record: encoder.fit(df_enc_big_na) msg = "Some of the variables in the dataset contain NaN. Check and remove those before using this transformer or set the par...
class RawLinesEditReplaceCommand(sublime_plugin.TextCommand): text = None region = None def run(self, edit): cls = RawLinesEditReplaceCommand if ((cls.text is not None) and (cls.region is not None)): self.view.replace(edit, cls.region, cls.text) cls.text = None cl...
class TestCAM16CAM16LCD(util.ColorAssertsPyTest): COLORS = [('red', 'color(--cam16-lcd 59.178 59.994 31.089)'), ('orange', 'color(--cam16-lcd 78.364 12.557 37.084)'), ('yellow', 'color(--cam16-lcd 96.802 -17.273 44.653)'), ('green', 'color(--cam16-lcd 46.661 -35.677 27.573)'), ('blue', 'color(--cam16-lcd 36.252 11....
def test_asset_store_collect2(): try: from flexx import ui except ImportError: skip('no flexx.ui') s = AssetStore() s.update_modules() assert (len(s.modules) > 10) assert ('flexx.ui._widget' in s.modules) assert ('$Widget =' in s.get_asset('flexx.ui._widget.js').to_string()) ...
def test_interpolate_vs_project(V): mesh = V.mesh() dim = mesh.geometric_dimension() if (dim == 2): (x, y) = SpatialCoordinate(mesh) elif (dim == 3): (x, y, z) = SpatialCoordinate(mesh) shape = V.ufl_element().value_shape if (dim == 2): if (len(shape) == 0): e...
class JsHtmlLi(JsHtmlRich): def has_state(self, state: str, js_funcs: types.JS_FUNCS_TYPES, profile: types.PROFILE_TYPE=None): return self.component.js.if_(('%s.classList.contains(%s)' % (self.varName, JsUtils.jsConvertData(state, None))), js_funcs, profile=profile) def is_active(self, js_funcs: types.J...
.parametrize('compiled', [True, False]) def test_bytes_integer_struct_signed(compiled): d = '\n struct test {\n int24 a;\n int24 b[2];\n int24 len;\n int24 dync[len];\n int24 c;\n int24 d[3];\n };\n ' c = cstruct.cstruct() c.load(d, compiled=com...
def extractWwwBlackboxTlCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type) in t...
class LiveDetails(): def __init__(self): self.spike_helper = GetSpike() self.shield_helper = GetShields() self.loadout_helper = GetLoadouts() self.header_agent_helper = GetLiveAgents() self.scoreboard_agents_helper = GetScoreBoardAgents() self.scoreboard_detector_help...
.parametrize('codec', ['snappy', 'zstandard', 'lz4']) .skipif(is_testing_cython_modules(), reason='difficult to monkeypatch builtins on cython compiled code') .skipif((os.name == 'nt'), reason='A pain to install codecs on windows') def test_optional_codecs_not_installed_reading(monkeypatch, codec): schema = {'doc':...
class Ui_WifiDialog(object): def setupUi(self, Dialog): Dialog.setObjectName('Dialog') Dialog.resize(372, 212) self.gridLayout_2 = QtWidgets.QGridLayout(Dialog) self.gridLayout_2.setObjectName('gridLayout_2') self.groupBox = QtWidgets.QGroupBox(Dialog) self.groupBox.s...
.parametrize('test_input,expected', [('2', (2, 0, 0)), ('2+', (3, 0, 0)), ('3', (3, 0, 0)), ('1.2.3', (1, 2, 3)), ('1.2.3-beta', (1, 2, 3))]) def test_python_version_parse(test_input, expected): f = StringIO(('\n [Core]\n Name = Config\n Module = config\n\n [Python]\n Version = %s\n ' % test_input...
class InformationDisplayer(ErsiliaBase): def __init__(self, info_data, config_json=None): ErsiliaBase.__init__(self, config_json=config_json, credentials_json=None) self.info_data = info_data self.logger.debug(self.info_data) def _echo(text, **styles): if (emoji is not None): ...
def make_st_acc_i8_s2_v2(p=st_acc_i8): p = rename(p, 'st_acc_i8_s2_v2') p = bind_config(p, 'scale', ConfigStore, 'scale') p = reorder_stmts(p, 'tmp : _ ; ConfigStore.scale = _') p = reorder_stmts(p, 'src_tmp = _ ; ConfigStore.scale = _') p = reorder_stmts(p, 'src_tmp : _ ; ConfigStore.scale = _') ...
class OptionSeriesPieStatesSelect(Options): def animation(self) -> 'OptionSeriesPieStatesSelectAnimation': return self._config_sub_data('animation', OptionSeriesPieStatesSelectAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): self._config(flag...
class OptionSeriesColumnrangeSonificationContexttracksMappingVolume(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 database_docs(request): (exports, extended_exports) = sql_statements.get_exports() toc = [] d = {'CORE_SCHEMA': {'title': 'The core bibliothecula schema.', 'caption': '', 'statements': exports}, 'EXTENDED_SCHEMA': {'title': 'Extra useful flair.', 'caption': 'A list of utility SQL statements for use with...
('ecs_deploy.cli.get_client') def test_deploy_s3_env_file_with_previous_value(get_client, runner): get_client.return_value = EcsTestClient('acces_key', 'secret_key') result = runner.invoke(cli.deploy, (CLUSTER_NAME, SERVICE_NAME, '--s3-env-file', 'webserver', 'arn:aws:s3:::centerfun/.env', '--s3-env-file', 'web...
class aggregate_stats_reply(stats_reply): version = 6 type = 19 stats_type = 2 def __init__(self, xid=None, flags=None, stats=None): if (xid != None): self.xid = xid else: self.xid = None if (flags != None): self.flags = flags else: ...
class socket(bsn_tlv): type = 212 def __init__(self, value=None): if (value != None): self.value = value else: self.value = 0 return def pack(self): packed = [] packed.append(struct.pack('!H', self.type)) packed.append(struct.pack('!H',...
class TestMarkForumsReadView(BaseClientTestCase): (autouse=True) def setup(self): self.u1 = UserFactory.create() self.u2 = UserFactory.create() self.g1 = GroupFactory.create() self.u1.groups.add(self.g1) self.u2.groups.add(self.g1) self.user.groups.add(self.g1) ...
class Integer(Integer32): def withNamedValues(cls, **values): enums = set(cls.namedValues.items()) enums.update(values.items()) class X(cls): namedValues = namedval.NamedValues(*enums) subtypeSpec = (cls.subtypeSpec + constraint.SingleValueConstraint(*values.values())...
class OptionSeriesPyramidSonificationDefaultinstrumentoptionsMapping(Options): def frequency(self) -> 'OptionSeriesPyramidSonificationDefaultinstrumentoptionsMappingFrequency': return self._config_sub_data('frequency', OptionSeriesPyramidSonificationDefaultinstrumentoptionsMappingFrequency) def gapBetwe...
class FadingDurationPreference(widgets.SpinPreference, widgets.CheckConditional): default = 50 name = 'plugin/desktopcover/fading_duration' condition_preference_name = 'plugin/desktopcover/fading' def __init__(self, preferences, widget): widgets.SpinPreference.__init__(self, preferences, widget)...
class TICKETER(): def __init__(self, target, password, domain, options): self.__password = password self.__target = target self.__domain = domain self.__options = options self.__tgt = None self.__tgt_session_key = None if options.spn: spn = options...
class Joystick(BaseJoystick): def __init__(self, disptype=settings.DISPTYPE, **args): if (disptype in ('pygame', 'psychopy')): from pygaze._joystick.pygamejoystick import PyGameJoystick self.__class__ = PyGameJoystick else: raise Exception('Unexpected disptype: {}...
class TestMatchIP(TestCase): def test_match_ip(self): self.assertFalse(utils.match_ip('192.168.0.1', '10.0.0.0/24')) self.assertTrue(utils.match_ip('192.168.0.1', '192.168.0.0/24')) self.assertTrue(utils.match_ip('192.168.0.1', '192.168.0.1')) self.assertFalse(utils.match_ip('192.168...
class DEP002UnusedDependenciesFinder(ViolationsFinder): def find(self) -> list[Violation]: logging.debug('\nScanning for unused dependencies...') unused_dependencies: list[Violation] = [] for dependency in self.dependencies: logging.debug('Scanning module %s...', dependency.name)...
class Solution(object): def longestPalindrome(self, s): tr = {} for c in s: if (c not in tr): tr[c] = 0 tr[c] += 1 odd_max = (- 1) r = 0 for (c, n) in tr.items(): if ((n % 2) == 0): r += n else: ...
class DummyPointGlyph(DummyGlyph): DrawingPen = DummyPointPen def appendGlyph(self, glyph): glyph.drawPoints(self._pen) def getPen(self): return SegmentToPointPen(self._pen) def getPointPen(self): return self._pen def draw(self, pen): pointPen = PointToSegmentPen(pen)...
def extractVertexGroup(from_path, to_path, hier_path): to_dir = '/'.join(to_path.split('/')[:(- 1)]) res_dir = '/'.join(hier_path.split('/')[:(- 1)]) if (not os.path.exists(to_dir)): os.makedirs(to_dir) if (not os.path.exists(res_dir)): os.makedirs(res_dir) objs = bpy.data.objects ...
class CopyTraits(object): def test_baz2_s(self): self.assertEqual(self.baz2.s, 'baz') self.assertEqual(self.baz2.s, self.baz.s) def test_baz2_bar_s(self): self.assertEqual(self.baz2.bar.s, 'bar') self.assertEqual(self.baz2.bar.s, self.baz.bar.s) def test_baz2_bar_foo_s(self):...
def test_pandas_annotations(): data = dict(a=['foo', 'bar'], b=[1, 2]) df1 = pd.DataFrame(data, columns=['a', 'b']) obj1 = Owner() assert (annotate(df1, obj1, foo=42) is df1) assert ('climetlab-0' in df1._metadata) a1 = annotation(df1) assert (a1.get('foo') == 42) assert (a1.owner is obj...
def update_treasury_appropriation_account_agencies(): sql = f''' with ata_mapping as ( select taa.treasury_account_identifier, ata.toptier_agency_id as awarding_toptier_agency_id from treasury_appropriation_account as taa ...
def test_types(): assert (TypeTransformer(None, type=EnumType(enum)).transform('a') == 'a') assert (TypeTransformer(None, type=EnumListType(enum)).transform('a') == ['a']) assert (TypeTransformer(None, type=StrType).transform(42) == '42') assert (TypeTransformer(None, type=StrListType).transform(42) == ...
def extractSnailtranslationWordpressCom(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, t...
class SDNEvents(): def __init__(self, logger, prom, sdnc): self.logger = logger self.prom = prom self.m_queue = queue.Queue() self.job_queue = queue.Queue() self.rabbits = [] self.config = Config().get_config() self.sdnc = sdnc self.sdnc.default_endpoi...
class OptionPlotoptionsArcdiagramSonificationDefaultinstrumentoptionsMappingLowpassFrequency(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 LocationRulesEngineTest(ForsetiTestCase): def setUp(self): location_rules_engine.LOGGER = mock.MagicMock() def test_build_rule_book_from_local_yaml_file(self): rule = rule_tmpl.format(mode='whitelist', type='bucket', ids=['*'], locations=['eu*']) rules_engine = get_rules_engine_wit...
def giou_loss(boxes1: torch.Tensor, boxes2: torch.Tensor, reduction: str='none', eps: float=1e-07) -> torch.Tensor: (x1, y1, x2, y2) = boxes1.unbind(dim=(- 1)) (x1g, y1g, x2g, y2g) = boxes2.unbind(dim=(- 1)) assert (x2 >= x1).all(), 'bad box: x1 larger than x2' assert (y2 >= y1).all(), 'bad box: y1 larg...
class RecordEventListenerTestCase(unittest.TestCase): def test_send(self): events = [] record = object() def e_handler(record, n=1): events.append(n) rle = quality_filter.RecordEventListener() rle.register_handler('e', e_handler) rle('e', record) s...
def upsert_privacy_experiences_after_config_update(db: Session, experience_config: PrivacyExperienceConfig, regions: List[PrivacyNoticeRegion]) -> Tuple[(List[PrivacyNoticeRegion], List[PrivacyNoticeRegion])]: linked_regions: List[PrivacyNoticeRegion] = [] current_regions: List[PrivacyNoticeRegion] = experience...
class VenueMessageFactory(MessageFactory): async def send_message(self, client: TelegramClient, chat_id: int, target: Message=None) -> Message: return (await client.send_message(chat_id, file=InputMediaVenue(InputGeoPoint(0.0, 0.0), 'Location name', f'Address {uuid4()}', '', '', ''), reply_to=target)) d...
class Flexx(): def __init__(self): if window.flexx.init: raise RuntimeError('Should not create global Flexx object more than once.') self.is_notebook = False self.is_exported = False for key in window.flexx.keys(): self[key] = window.flexx[key] self.ne...
class UserRelated(BaseObject): def __init__(self, api=None, assigned_tickets=None, ccd_tickets=None, entry_subscriptions=None, forum_subscriptions=None, organization_subscriptions=None, requested_tickets=None, subscriptions=None, topic_comments=None, topics=None, votes=None, **kwargs): self.api = api ...
class Test_mldv2_query(unittest.TestCase): type_ = 130 code = 0 csum = 46500 maxresp = 10000 address = 'ff08::1' s_flg = 0 qrv = 2 s_qrv = ((s_flg << 3) | qrv) qqic = 10 num = 0 srcs = [] mld = icmpv6.mldv2_query(maxresp, address, s_flg, qrv, qqic, num, srcs) buf = ((...
def test_01_09_predictions(nlp): text = "Apple : le nouveau modele X Pro attendu pour l'ete." doc = nlp(text) ents = [(ent.text, ent.label_) for ent in doc.ents] assert (len(ents) == 1) assert (ents[0] == ('Apple', 'ORG')) assert (doc[5].ent_type == 0) assert (doc[6].ent_type == 0)
class AnimatedPlot(HasTraits): x_values = Any() y_values = Array() color = Str() plot = Instance(Component) def _plot_default(self): if (type(self.x_values) == ArrayDataSource): self.x_values = self.x_values.get_data()[:] plot = create_line_plot((self.x_values, self.y...
class io_dict_toml_test_case(io_dict_test_case): def test_from_toml_with_valid_data(self): j = '\na = 1\n\n[b]\nc = 3\nd = 4\n' d = IODict.from_toml(j) self.assertTrue(isinstance(d, dict)) self.assertEqual(d, {'a': 1, 'b': {'c': 3, 'd': 4}}) d = IODict(j, format='toml') ...
class TransferProgress(object): def __init__(self, tp): self.total_objects = tp.total_objects self.indexed_objects = tp.indexed_objects self.received_objects = tp.received_objects self.local_objects = tp.local_objects self.total_deltas = tp.total_deltas self.indexed_d...
class TestDicts(testslide.TestCase): def testAnyDict(self): self.assertEqual(testslide.matchers.AnyDict(), {}) self.assertEqual(testslide.matchers.AnyDict(), {'a': 1}) self.assertNotEqual(testslide.matchers.AnyDict(), 69) self.assertNotEqual(testslide.matchers.AnyDict(), []) ...
class TestIndexListFilterAllocated(TestCase): def builder(self, key='2'): self.client = Mock() self.client.info.return_value = get_es_ver() self.client.cat.indices.return_value = get_testvals(key, 'state') self.client.indices.get_settings.return_value = get_testvals(key, 'settings') ...
def test_schedule_with_lp(): def double(a: int) -> int: return (a * 2) def quadruple(a: int) -> int: b = double(a=a) c = double(a=b) return c lp = LaunchPlan.create('schedule_test', quadruple, schedule=FixedRate(_datetime.timedelta(hours=12), 'kickoff_input')) assert (lp....
def main(page: Page): page.add(Row([Container(bgcolor=colors.ORANGE_300, alignment=alignment.center, expand=True), VerticalDivider(), Container(bgcolor=colors.BROWN_400, alignment=alignment.center, expand=True), VerticalDivider(width=1, color='white'), Container(bgcolor=colors.BLUE_300, alignment=alignment.center, ...
class KeyInstanceFlag(IntFlag): NONE = 0 IS_ACTIVE = (1 << 0) USER_SET_ACTIVE = (1 << 8) IS_PAYMENT_REQUEST = (1 << 9) IS_INVOICE = (1 << 10) CACHE_MASK = IS_ACTIVE ACTIVE_MASK = (IS_ACTIVE | USER_SET_ACTIVE) INACTIVE_MASK = (~ IS_ACTIVE) ALLOCATED_MASK = (IS_PAYMENT_REQUEST | IS_INV...
def run(): ovlp_types = 'wf tden nto_org nto'.split() ovlp_withs = 'adapt first previous'.split() for (i, (ovlp_type, ovlp_with)) in enumerate(it.product(ovlp_types, ovlp_withs)): print(highlight_text(f'i={i:02d}, ovlp_type={ovlp_type}, ovlp_with={ovlp_with}')) geom = geom_from_library('cyto...
def create_emp(emp): doc = frappe.new_doc('Employee') doc.zenoti_employee_id = emp['id'] doc.zenoti_employee_code = emp['code'] doc.zenoti_employee_username = (emp['personal_info']['user_name'] if ('user_name' in emp['personal_info']) else '') doc.first_name = emp['personal_info']['first_name'] ...
class FerryFeeHandler(THBEventHandler): interested = ['action_after'] def handle(self, evt_type, act): if ((evt_type == 'action_after') and isinstance(act, Damage)): src = act.source tgt = act.target if (not (src and src.has_skill(FerryFee))): return a...