code
stringlengths
281
23.7M
def _unpack_ext(code, read_fn): if (code == b'\xd4'): length = 1 elif (code == b'\xd5'): length = 2 elif (code == b'\xd6'): length = 4 elif (code == b'\xd7'): length = 8 elif (code == b'\xd8'): length = 16 elif (code == b'\xc7'): length = _struct_u...
(tags=['financial'], description=docs.TOTALS, params={'entity_type': {'description': 'Committee groupings based on FEC filing form. Choose one of: `presidential`, `pac`, `party`, `pac-party`, `house-senate`, or `ie-only`', 'enum': ['presidential', 'pac', 'party', 'pac-party', 'house-sena...
def gen_oxm_defines(out): out.write("\n/*\n * The generic match structure uses the OXM bit indices for it's\n * bitmasks for active and masked values\n */\n") for (key, entry) in match.of_match_members.items(): out.write(('\n/* Mask/value check/set macros for %(key)s */\n\n/**\n * Set the mask for an ex...
class DABSSubmissionWindowSchedule(models.Model): id = models.IntegerField(primary_key=True) period_start_date = models.DateTimeField() period_end_date = models.DateTimeField() submission_start_date = models.DateTimeField() submission_due_date = models.DateTimeField() certification_due_date = mo...
class OptionSeriesArearangeSonificationTracksMappingTremoloDepth(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 EventUserModelViewSet(viewsets.ModelViewSet): filter_fields = ('event_user__event__event_slug',) ordering_fields = ('created_at', 'updated_at') search_fields = None def get_counts(self): model = self.serializer_class.Meta.model queryset = self.filter_queryset(self.get_queryset()) ...
def test_paper_example_figure_2a(): (x0, x1, x2) = [Variable('x', Integer.int32_t(), i) for i in range(3)] (z0, z1, z2) = [Variable('z', Integer.int32_t(), i) for i in range(3)] (y0, y1) = [Variable('y', Integer.int32_t(), i) for i in range(2)] (bar, qux) = [Call(FunctionSymbol(name, 66), []) for name i...
def binned_profile(y, x, bins=20, statistic='mean'): if np.isscalar(bins): if (bins <= 0): raise RuntimeError('The number of bins should be positive.') bins = np.linspace(np.min(x), np.max(x), (bins + 1)) bin_centers = ((bins[1:] + bins[:(- 1)]) / 2) num_bins = len(bin_centers) ...
class TraceFrame(Base, PrepareMixin, RecordMixin): __tablename__ = 'trace_frames' __table_args__ = ((Index('ix_traceframe_run_caller_port', 'run_id', 'caller_id', 'caller_port'), Index('ix_traceframe_run_callee_port', 'run_id', 'callee_id', 'callee_port')) + BASE_TABLE_ARGS) id: DBID = Column(BIGDBIDType, n...
_os(*metadata.platforms) def main(): import ctypes, platform from ctypes import windll, wintypes kernel32 = windll.kernel32 LoadLibraryA = kernel32.LoadLibraryA LoadLibraryA.argtypes = [wintypes.LPCSTR] LoadLibraryA.restype = wintypes.HMODULE GetProcAddress = kernel32.GetProcAddress GetP...
class IdModifyMixin(object): def setUp(self): self.input_fp = StringIO(self.initial_fasta) self.output_fp = StringIO() def test_modify(self): records = SeqIO.parse(self.input_fp, 'fasta') records = self.__class__.modify_fn(records) SeqIO.write(records, self.output_fp, 'fa...
('/verify/', methods=['GET', 'POST']) _cache_control_no_store() def verify(): method = verification_service.get_method() verified = False verified_message = None if (request.method == 'POST'): if (not check_csrf_referer(request)): raise BadRequestError('Bad referer header') i...
() def large_snapshot() -> Snapshot: builder = SnapshotBuilder() for i in range(0, 150): builder.add_forward_model(forward_model_id=str(i), index=str(i), name=f'job_{i}', current_memory_usage='500', max_memory_usage='1000', status=FORWARD_MODEL_STATE_START, stdout=f'job_{i}.stdout', stderr=f'job_{i}.std...
def compare_score_to_db(): if ah.user_settings['keep_log']: ah.log.debug('Begin function') if (not be_ready()): if ah.user_settings['keep_log']: ah.log.error('compare score: not ready') return False if ((ah.habitica.hnote != None) and ah.habitica.hnote['scoresincedate']):...
def test_duplicate(a, bcs): (test, trial) = a.arguments() if (test.function_space().shape == ()): rhs_form = (inner(Constant(1), test) * dx) elif (test.function_space().shape == (2,)): rhs_form = (inner(Constant((1, 1)), test) * dx) if (bcs is not None): Af = assemble(a, mat_type...
class DependencyNotFound(Exception): def __init__(self, configuration_file: Path, expected_deps: Set[PackageId], missing_dependencies: Set[PackageId], *args: Any) -> None: super().__init__(*args) self.configuration_file = configuration_file self.expected_dependencies = expected_deps ...
def main(distribution): _update_package_sources(distribution) _update_submodules() BIN_DIR.mkdir(exist_ok=True) apt_packages_path = (INSTALL_DIR / 'apt-pkgs-common.txt') dnf_packages_path = (INSTALL_DIR / 'dnf-pkgs-common.txt') if (distribution != 'fedora'): pkgs = read_package_list_from...
class BufferedReader(): __slots__ = ['_buffer', '_buffer_len', '_buffer_pos', '_chunk_size', '_consumed', '_exhausted', '_iteration_started', '_max_join_size', '_source'] def __init__(self, source, chunk_size=None): self._source = self._iter_normalized(source) self._chunk_size = (chunk_size or D...
def status_code_from_response(result): if (type(result) == str): return 200 status_code = 200 if isinstance(result, tuple): status_code = result[1] else: try: status_code = getattr(result, 'status_code') except: pass if (not is_valid_status_cod...
class TestFunctions(unittest.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp() KM.CONF_FILE = os.path.join(self.tmpdir, 'keepmenu-config.ini') def tearDown(self): rmtree(self.tmpdir) def test_config_option(self): KM.reload_config(os.path.join(self.tmpdir, 'config.i...
def from_mininet(topology): fnss_topo = Topology(capacity_unit='Mbps') for v in topology.switches(): fnss_topo.add_node(v, type='switch') for v in topology.hosts(): fnss_topo.add_node(v, type='host') for (u, v) in topology.links(): fnss_topo.add_edge(u, v) opts = topology...
class GifWriter(object): def __init__(self, filename, framerate=15): self.is_closed = False self.filename = filename self.framerate = framerate self._frames = [] def num_frames(self): return len(self._frames) def __del__(self): try: self.close() ...
class PythonDataType(DataType, PythonType): def __init__(self, kernel, supertypes={Any}): self.kernel = kernel def __le__(self, other): if isinstance(other, PythonDataType): return issubclass(self.kernel, other.kernel) return NotImplemented def validate_instance(self, obj...
class ResBlock(nn.Module): def __init__(self, inp, bam, kernel_size=3, bias=True, bn=False, act=nn.ReLU(True), res_scale=1): super(ResBlock, self).__init__() modules = [] for i in range(2): modules.append(conv(inp, inp, kernel_size, bias=bias)) if bn: ...
def convert_settings_to_toml_docs(settings_name: str, settings: BaseSettings) -> str: settings_schema = settings.schema() included_keys = set(settings.dict().keys()) title_header = build_section_header(settings_name) settings_description = settings_schema['description'] settings_docstring = f'''[{se...
.skipif((not sys.platform.startswith('linux')), reason='Linux-specific socket behaviour') def test_reuse_passive_live_linux_nok_ok(unused_tcp_port): custom_range = range(unused_tcp_port, (unused_tcp_port + 1)) (_, port, orig_sock) = port_handler.find_available_port(custom_range=custom_range, custom_host='127.0....
class OVSBridge(object): def __init__(self, CONF, datapath_id, ovsdb_addr, timeout=None, exception=None, br_name=None): super(OVSBridge, self).__init__() self.datapath_id = datapath_id self.ovsdb_addr = ovsdb_addr self.vsctl = ovs_vsctl.VSCtl(ovsdb_addr) self.timeout = (timeo...
def load_configuration(package_type: PackageType, package_path: Path) -> PackageConfiguration: configuration_class = type_to_class_config[package_type] configuration_filepath = (package_path / configuration_class.default_configuration_filename) loader = ConfigLoaders.from_package_type(package_type) with...
class OptionSeriesFunnel3dSonificationTracksMappingTremoloDepth(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 plot_check(fig, condition, color_options: ColorOptions): lines = [] left_line = pd.Series([condition.gt, condition.gte]).max() if (not pd.isnull(left_line)): left_line_name = ['gt', 'gte'][pd.Series([condition.gt, condition.gte]).argmax()] lines.append((left_line, left_line_name)) ri...
_required _required _required def dc_user_list(request): (user, dc) = (request.user, request.dc) users = User.objects.order_by('username').filter(ExcludeInternalUsers) context = collect_view_data(request, 'dc_user_list') context['is_staff'] = is_staff = user.is_staff context['can_edit'] = can_edit =...
def test_react(): with LocalNode() as node: agent_name = 'MyAgent' private_key_path = os.path.join(CUR_PATH, 'data', DEFAULT_PRIVATE_KEY_FILE) builder = AEABuilder() builder.set_name(agent_name) builder.add_private_key(DEFAULT_LEDGER, private_key_path) builder.add_pro...
class Faucet8021XVLANTest(Faucet8021XSuccessTest): CONFIG_GLOBAL = ('vlans:\n 100:\n vid: 100\n description: "untagged"\n radiusassignedvlan1:\n vid: %u\n description: "untagged"\n dot1x_assigned: True\n radiusassignedvlan2:\n vi...
def test_entity_storage_is_in_storage_asset(create_test_db, create_project, prepare_entity_storage): from stalker import Asset, Task, Version project = create_project char1 = Asset.query.filter((Asset.project == project)).filter((Asset.name == 'Char1')).first() model = Task.query.filter((Task.parent == ...
def test_ijk_to_ib(): ib = xcalc.ijk_to_ib(2, 2, 2, 3, 4, 5) assert (ib == 16) ib = xcalc.ijk_to_ib(3, 1, 1, 3, 4, 5) assert (ib == 2) ic = xcalc.ijk_to_ib(2, 2, 2, 3, 4, 5, forder=False) assert (ic == 26) ic = xcalc.ijk_to_ib(3, 1, 1, 3, 4, 5, forder=False) assert (ic == 40)
_only_with_numba def test_equivalent_sources_spherical(): region = ((- 70), (- 60), (- 40), (- 30)) radius = 6400000.0 points = vd.grid_coordinates(region=region, shape=(6, 6), extra_coords=(radius - 500000.0)) masses = vd.synthetic.CheckerBoard(amplitude=.0, region=region).predict(points) coordinat...
class GANTrainApp(BaseTrainApp): def __init__(self, module: GANModuleConf, trainer: TrainerConf, datamodule: DataModuleConf) -> None: super().__init__(module, trainer, datamodule) def get_data_module(self) -> Optional[LightningDataModule]: return hydra.utils.instantiate(self.datamodule_conf) ...
def test_self_attribute_alt_name_explicit_2(): class Container(containers.DeclarativeContainer): foo = providers.Self() bar = foo container = Container() assert (container.__self__ is container.foo) assert (container.__self__ is container.bar) assert (set(container.__self__.alt_names...
class OAuthAccountRepository(BaseRepository[OAuthAccount], UUIDRepositoryMixin[OAuthAccount]): model = OAuthAccount async def get_by_provider_and_account_id(self, provider_id: UUID4, account_id: str) -> (OAuthAccount | None): statement = select(OAuthAccount).where((OAuthAccount.oauth_provider_id == prov...
class ImportUIKitModule(fb.FBCommand): def name(self): return 'uikit' def description(self): return 'Imports the UIKit module to get access to the types while in lldb.' def run(self, arguments, options): frame = lldb.debugger.GetSelectedTarget().GetProcess().GetSelectedThread().GetSe...
class lr_all_enabled(bsn_tlv): type = 178 def __init__(self): return def pack(self): packed = [] packed.append(struct.pack('!H', self.type)) packed.append(struct.pack('!H', 0)) length = sum([len(x) for x in packed]) packed[1] = struct.pack('!H', length) ...
(suppress_health_check=[HealthCheck.function_scoped_fixture]) (xtgeo_grids, units, units, st.sampled_from(['grdecl', 'bgrdecl', 'egrid', 'fegrid'])) def test_grid_to_file_conversion(tmp_path, xtgeo_grid, unit1, unit2, fformat): filepath = (tmp_path / ('grid.' + fformat)) xtgeo_grid.units = unit1 xtgeo_grid....
def test_decoding_unknown_performative(): msg = FipaMessage(performative=FipaMessage.Performative.ACCEPT) encoded_msg = FipaMessage.serializer.encode(msg) with pytest.raises(ValueError, match='Performative not valid:'): with mock.patch.object(FipaMessage.Performative, '__eq__', return_value=False): ...
.parametrize('domain_data, message_types, message_data, expected_sig', (({'name': 'Ether Mail', 'version': '1', 'chainId': 1, 'verifyingContract': '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC'}, {'Person': [{'name': 'name', 'type': 'string'}, {'name': 'wallet', 'type': 'address'}], 'Mail': [{'name': 'from', 'type': 'Per...
() ('ip') ('-i', 'interface', default=None, help='Wich interface to use (default: auto)') ('-c', 'count', default=0, help='How many packets send (default: infinit)') ('-t', 'timeout', default=2, help='Timeout in seconds (default: 2)') ('-w', 'wait', default=1, help='How many seconds between packets (default: 1)') ('-v'...
(params=['circlemanifold', 'icosahedron', 'cubedsphere']) def hedgehog_mesh(request): if (request.param == 'circlemanifold'): base = CircleManifoldMesh(ncells=3, radius=(1 / np.sqrt(27))) elif (request.param == 'icosahedron'): base = IcosahedralSphereMesh((np.sin(((2 * np.pi) / 5)) * np.sqrt((1 ...
def test_adding_deprecated_labels(): config = '\ndeployment:\n enabled: true\nlabels:\n app-test: filebeat\n' r = helm_template(config) assert (r['daemonset'][name]['metadata']['labels']['app-test'] == 'filebeat') assert (r['deployment'][name]['metadata']['labels']['app-test'] == 'filebeat') asser...
class BasePenTest(unittest.TestCase): def test_moveTo(self): pen = _TestPen() pen.moveTo((0.5, (- 4.3))) self.assertEqual('0.5 -4.3 moveto', repr(pen)) self.assertEqual((0.5, (- 4.3)), pen.getCurrentPoint()) def test_lineTo(self): pen = _TestPen() pen.moveTo((4, 5...
class TestxyYSerialize(util.ColorAssertsPyTest): COLORS = [('color(--xyy 0 0.3 0.75 / 0.5)', {}, 'color(--xyy 0 0.3 0.75 / 0.5)'), ('color(--xyy 0 0.3 0.75)', {'alpha': True}, 'color(--xyy 0 0.3 0.75 / 1)'), ('color(--xyy 0 0.3 0.75 / 0.5)', {'alpha': False}, 'color(--xyy 0 0.3 0.75)'), ('color(--xyy none 0.3 0.75)...
class OptionPlotoptionsHistogramSonificationDefaultinstrumentoptionsMappingNoteduration(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(se...
class CommaSeparatedUUIDField(CharField): default_error_messages = {'invalid': _('Enter only valid UUIDs separated by commas.')} def prepare_value(self, value): if isinstance(value, (list, tuple)): return ','.join(map(text_type, value)) return value def to_python(self, value): ...
def filter_log_syslogd4_setting_data(json): option_list = ['certificate', 'custom_field_name', 'enc_algorithm', 'facility', 'format', 'interface', 'interface_select_method', 'max_log_rate', 'mode', 'port', 'priority', 'server', 'source_ip', 'ssl_min_proto_version', 'status', 'syslog_type'] json = remove_invalid...
class Slice(): def __init__(self, name, value, index, is_dimension, is_info): self.name = name self.index = index self.value = value self.is_dimension = ((not is_info),) self.is_info = is_info def __repr__(self): return ('[%s:%s=%s]' % (self.name, self.index, self...
def test_when_input_is_pandas_columns(df_vartypes): input_features = df_vartypes.columns transformer = MockTransformer() transformer.fit(df_vartypes) assert (transformer.get_feature_names_out(input_features=input_features) == variables_str) transformer.fit(df_vartypes.to_numpy()) assert (transfo...
def prepare_timestamp_millis(data, schema): if isinstance(data, datetime.datetime): if (data.tzinfo is not None): delta = (data - epoch) return (((((delta.days * 24) * 3600) + delta.seconds) * MLS_PER_SECOND) + int((delta.microseconds / 1000))) if is_windows: delt...
.django_db def test_sort_columns(client, create_idv_test_data): for sortable_column in SORTABLE_COLUMNS: _test_post(client, {'award_id': 2, 'order': 'desc', 'sort': sortable_column}, (None, None, 1, False, False, 14, 13, 12, 11, 10, 9, 8, 7, 2)) _test_post(client, {'award_id': 2, 'order': 'asc', 'so...
.usefixtures('use_tmpdir') def test_analysis_config_from_file_is_same_as_from_dict(): with open('analysis_config', 'w', encoding='utf-8') as fout: fout.write(dedent('\n NUM_REALIZATIONS 10\n MIN_REALIZATIONS 10\n ANALYSIS_SET_VAR STD_ENKF ENKF_TRUNCATION 0.8\n ...
def build_tunnel_ofmsgs(rule_conf, acl_table, priority, port_num=None, vlan_vid=None, flowdel=False, reverse=False): ofmsgs = [] acl_inst = [] acl_match = [] acl_match_dict = {} (_, output_actions, output_ofmsgs, output_inst) = build_output_actions(acl_table, rule_conf) ofmsgs.extend(output_ofms...
class _TTGlyphGlyf(_TTGlyph): def draw(self, pen): (glyph, offset) = self._getGlyphAndOffset() with self.glyphSet.pushDepth() as depth: if depth: offset = 0 if glyph.isVarComposite(): self._drawVarComposite(glyph, pen, False) re...
class Strategy(): def __init__(self, symbols, capital, start, end, options=default_options): self.symbols = symbols self.capital = capital self.start = start self.end = end self.options = options.copy() self.ts = None self.rlog = None self.tlog = None ...
def test_logger_with_exc_info(logbook_logger, logbook_handler): with logbook_handler.applicationbound(): try: raise ValueError('This is a test ValueError') except ValueError: logbook_logger.info('This is a test info with an exception', exc_info=True) assert (len(logbook_h...
def test_providers_with_default_value_overriding(config): config.set_default({'a': {'b': {'c': 1, 'd': 2}}}) assert (config.a() == {'b': {'c': 1, 'd': 2}}) assert (config.a.b() == {'c': 1, 'd': 2}) assert (config.a.b.c() == 1) assert (config.a.b.d() == 2) config.override({'a': {'b': {'c': 3, 'd'...
def get_linear_bend_inds(coords3d, cbm, bends, min_deg=175, max_bonds=4, logger=None): linear_bends = list() complements = list() if (min_deg is None): return (linear_bends, complements) bm = squareform(cbm) for bend in bends: deg = np.rad2deg(Bend._calculate(coords3d, bend)) ...
def test_inforec_empty_components(): path = 'data/lis/records/inforec_08.lis' (f,) = lis.load(path) wellsite = f.wellsite_data()[0] assert wellsite.isstructured() table = wellsite.table(simple=True) mnem = np.array(['MN1 ', 'MN2 '], dtype='O') np.testing.assert_array_equal(table['MNEM'], mne...
def get_episodes(html, url): path = urlparse(url).path pattern = '<a href="({}[^"]+)[^>]*?><span>([^<]+)'.format(path) s = [] for match in re.finditer(pattern, html): (ep_url, ep_title) = match.groups() s.append(Episode(ep_title, urljoin(url, ep_url))) return s[::(- 1)]
def main(): mpi_env_params = comms_utils.read_comms_env_vars() dlrmBench = commsDLRMBench() parser = argparse.ArgumentParser(description='PARAM-Comms DLRM Benchmark', formatter_class=argparse.ArgumentDefaultsHelpFormatter) args = dlrmBench.readArgs(parser) dlrmBench.checkArgs(args) dlrmBench.ini...
.django_db() def test_state_current_all_years_success(client, state_data): expected_response = EXPECTED_STATE.copy() expected_response.update({'pop_year': CURRENT_FISCAL_YEAR, 'mhi_year': (CURRENT_FISCAL_YEAR - 2), 'award_amount_per_capita': None, 'total_prime_awards': 2, 'total_prime_amount': 200000}) resp...
.parallel(nprocs=4) def test_split_communicators(): wcomm = COMM_WORLD if (wcomm.rank == 0): wcomm.Split(MPI.UNDEFINED) m = UnitTriangleMesh(comm=COMM_SELF) V = FunctionSpace(m, 'DG', 0) u = TrialFunction(V) v = TestFunction(V) volume = assemble((inner(u, v) * dx)...
class Firewall(): def __init__(self, offline=False): self._firewalld_conf = firewalld_conf(config.FIREWALLD_CONF) self._offline = offline if (not offline): self.ip4tables_backend = ipXtables.ip4tables(self) self.ip6tables_backend = ipXtables.ip6tables(self) ...
.skip(reason='these notebooks need special software or hardware') .parametrize('nb_file', ('examples/00_intro_to_thinc.ipynb', 'examples/02_transformers_tagger_bert.ipynb', 'examples/03_pos_tagger_basic_cnn.ipynb', 'examples/03_textcat_basic_neural_bow.ipynb', 'examples/04_configure_gpu_memory.ipynb', 'examples/04_para...
def test_transform_raises_error_if_df_contains_na(df_enc, df_enc_na): encoder = MeanEncoder() encoder.fit(df_enc[['var_A', 'var_B']], df_enc['target']) with pytest.raises(ValueError) as record: encoder.transform(df_enc_na[['var_A', 'var_B']]) msg = "Some of the variables in the dataset contain N...
class FakeUserAgent(): def __init__(self, browsers=['chrome', 'edge', 'firefox', 'safari'], os=['windows', 'macos', 'linux'], min_percentage=0.0, fallback='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36', safe_attrs=tuple()): assert isinstance...
class ChangeTest(unittest.TestCase): def test_change_for_1_cent(self): self.assertEqual(find_fewest_coins([1, 5, 10, 25], 1), [1]) def test_single_coin_change(self): self.assertEqual(find_fewest_coins([1, 5, 10, 25, 100], 25), [25]) def test_multiple_coin_change(self): self.assertEqu...
class OptionSeriesColumnrangeSonificationDefaultinstrumentoptionsMapping(Options): def frequency(self) -> 'OptionSeriesColumnrangeSonificationDefaultinstrumentoptionsMappingFrequency': return self._config_sub_data('frequency', OptionSeriesColumnrangeSonificationDefaultinstrumentoptionsMappingFrequency) ...
def _check_awards_for_deletes(id_list: list, spark: 'pyspark.sql.SparkSession'=None, awards_table: str='vw_awards') -> list: formatted_value_ids = '' for x in id_list: formatted_value_ids += (("('" + x) + "'),") sql = '\n SELECT x.generated_unique_award_id\n FROM (values {ids}) AS x(ge...
def test_error_attr_ignore(): html = '\n<input type="text" name="foo" value="bar" data-formencode-form="a" />\n<input type="text" name="foo" value="biz" data-formencode-form="b" />\n<input type="text" name="foo" value="bash" data-formencode-form="c" />\n' expected_html = '\n<input type="text" name="foo" value="...
class OptionSeriesItemSonificationDefaultinstrumentoptionsMappingHighpass(Options): def frequency(self) -> 'OptionSeriesItemSonificationDefaultinstrumentoptionsMappingHighpassFrequency': return self._config_sub_data('frequency', OptionSeriesItemSonificationDefaultinstrumentoptionsMappingHighpassFrequency) ...
class AuditLogMessage(StrEnum): OBJECT_CREATED = 'OBJECT_CREATED' OBJECT_UPDATED = 'OBJECT_UPDATED' OBJECT_DELETED = 'OBJECT_DELETED' USER_REGISTERED = 'USER_REGISTERED' USER_UPDATED = 'USER_UPDATED' USER_EMAIL_VERIFY_REQUESTED = 'USER_EMAIL_VERIFY_REQUESTED' USER_FORGOT_PASSWORD_REQUESTED =...
class CustomJsonDataset(torch.utils.data.IterableDataset): def __init__(self, dataset, tokenizer, block_size=1024): raw_data = dataset self.tokenizer = tokenizer self.block_size = block_size tokenized_datasets = [] for d in raw_data: tokenized_datasets.append(self...
class JsArray(JsObject.JsObject): _jsClass = 'Array' def length(self): from epyk.core.js.primitives import JsNumber return JsNumber.JsNumber(('%s.length' % self.varId), is_py_data=False) def set(cls, js_code: str, data: Optional[list]=None, page: primitives.PageModel=None): if (data ...
class PostCardMigrationHandler(EventArbiter): game: THBattle handlers: Sequence[THBEventHandler] interested = ['post_card_migration'] def handle(self, evt_type, arg): if (evt_type != 'post_card_migration'): return arg g = self.game act = arg.action tgt = (act....
(IClipboard) class Clipboard(BaseClipboard): def _get_has_data(self): result = False with _ensure_clipboard(): if cb.Open(): with _close_clipboard(): result = (cb.IsSupported(TextFormat) or cb.IsSupported(FileFormat) or cb.IsSupported(PythonObjectForma...
class IdentityWithNextObservationTrajectoryProcessor(TrajectoryProcessor): (TrajectoryProcessor) def convert_trajectory_with_env(trajectory: TrajectoryRecord, conversion_env: Optional[MazeEnv]) -> List[StructuredSpacesRecord]: spaces_records = [] for (step_id, step_record) in enumerate(trajector...
def test_lifting_no_unnecessary_assignment(variable_v, variable_u, construct_stage_for_lifting): (phi_fct_lifter, instructions, nodes) = construct_stage_for_lifting old_edges = set(phi_fct_lifter.interference_graph.edges()) phi_fct_lifter.lift() new_edges = set(phi_fct_lifter.interference_graph.edges())...
class Pod(object): pod_spec: k8s_models.V1PodSpec primary_container_name: str = PRIMARY_CONTAINER_DEFAULT_NAME labels: Optional[Dict[(str, str)]] = None annotations: Optional[Dict[(str, str)]] = None def __post_init__(self): if (not self.pod_spec): raise _user_exceptions.FlyteVal...
def test_lp_each_parameter(): def t1(a: int) -> typing.NamedTuple('OutputsBC', t1_int_output=int, c=str): a = (a + 2) return (a, ('world-' + str(a))) def wf(a: int, c: str) -> (int, str): (x, y) = t1(a=a) return (x, y) launch_plan.LaunchPlan.get_or_create(workflow=wf, name='g...
class OptionSeriesAreasplineDataMarkerStates(Options): def hover(self) -> 'OptionSeriesAreasplineDataMarkerStatesHover': return self._config_sub_data('hover', OptionSeriesAreasplineDataMarkerStatesHover) def normal(self) -> 'OptionSeriesAreasplineDataMarkerStatesNormal': return self._config_sub_...
def test_align_concatenate_to_nexus(o_dir, e_dir, request): program = 'bin/align/phyluce_align_concatenate_alignments' output = os.path.join(o_dir, 'mafft-gblocks-clean-concat-nexus') cmd = [os.path.join(request.config.rootdir, program), '--alignments', os.path.join(e_dir, 'mafft-gblocks-clean'), '--output'...
def compile_cached(path_src): grammar = get_solidity_grammar_instance() path_src = Path(path_src) path_cache = (path_src.parent / 'cache') if (not path_cache.exists()): path_cache.mkdir() path_ast_json = (path_cache / (path_src.name + '.ast_json')) path_ast = (path_cache / (path_src.name...
def test_make_plural_is_working_properly(): from stalker.models import make_plural test_words = [('asset', 'assets'), ('client', 'clients'), ('department', 'departments'), ('entity', 'entities'), ('template', 'templates'), ('group', 'groups'), ('format', 'formats'), ('link', 'links'), ('session', 'sessions'), (...
def test_map_task_override(serialization_settings): def my_mappable_task(a: int) -> typing.Optional[str]: return str(a) def wf(x: typing.List[int]): array_node_map_task(my_mappable_task)(a=x).with_overrides(container_image='random:image') assert (wf.nodes[0].run_entity.container_image == 'ra...
def test_no_dict_action_wrapper(): base_env = GymMazeEnv(env='CartPole-v0') env = NoDictActionWrapper.wrap(base_env) assert isinstance(env.action_space, spaces.Discrete) assert isinstance(env.action_spaces_dict, dict) action = env.action_space.sample() out_action = env.action(action) assert ...
class TestCompositing(util.ColorAsserts, unittest.TestCase): def test_disable_compose(self): c1 = Color('#07c7ed').set('alpha', 0.5).compose('#fc3d99', blend='multiply', operator=False, space='srgb') c2 = c1.compose('#fc3d99', blend=False, space='srgb') self.assertColorEqual(Color('#07c7ed')...
class QtHandler(QtHandlerBase): char_signal = pyqtSignal(object) pin_signal = pyqtSignal(object) def __init__(self, win, device): super(QtHandler, self).__init__(win, device) self.char_signal.connect(self.update_character_dialog) self.pin_signal.connect(self.pin_dialog) self....
def dirs_report(jobs: typing.List[job.Job], dir_cfg: configuration.Directories, arch_cfg: typing.Optional[configuration.Archiving], sched_cfg: configuration.Scheduling, width: int) -> str: dst_dir = dir_cfg.get_dst_directories() reports = [tmp_dir_report(jobs, dir_cfg, sched_cfg, width), dst_dir_report(jobs, ds...
def set_context_menu_style(graph: NodeGraph, text_color, bg_color, selected_color, disabled_text_color=None): context_menu: NodeGraphMenu = graph.get_context_menu('graph').qmenu style = get_context_menu_stylesheet(text_color, bg_color, selected_color, disabled_text_color) context_menu.setStyleSheet(style)
def GET_MESSAGE_TYPE(command): if (command[0:2] == 'S_'): return MessageType.ServerMessage elif (command[(- 7):] == 'Request'): return MessageType.PlayerRequest elif (command[(- 8):] == 'Response'): return MessageType.PlayerResponse else: return MessageType.UnknownMessage
def validate_ticket_holders(ticket_holder_ids): ticket_holders = TicketHolder.query.filter_by(deleted_at=None).filter(TicketHolder.id.in_(ticket_holder_ids)).all() if (len(ticket_holders) != len(ticket_holder_ids)): logger.warning('Ticket Holders not found in', extra=dict(ticket_holder_ids=ticket_holder...
class HasSlices(HasStrictTraits): my_slice = Instance(slice) also_my_slice = Slice() none_explicitly_allowed = Instance(slice, allow_none=True) also_allow_none = Slice(allow_none=True) disallow_none = Instance(slice, allow_none=False) also_disallow_none = Slice(allow_none=False)
class ExtensionPointChangedTestCase(unittest.TestCase): def test_set_extension_point(self): a = PluginA() application = SimpleApplication(plugins=[a]) application.start() with self.assertRaises(TypeError): setattr(a, 'x', [1, 2, 3]) def test_mutate_extension_point_no_...