code
stringlengths
281
23.7M
def exposed_astor_roundtrip_parser_functions(): with db.session_context() as sess: res = sess.query(db.RssFeedEntry).all() for row in res: func = row.get_func() _ast = row._get_ast() src = astor.to_source(_ast, indent_with='\t', pretty_source=better_pretty_source)...
def test_list_saml_provider_configs(sample_tenant, saml_provider): client = tenant_mgt.auth_for_tenant(sample_tenant.tenant_id) page = client.list_saml_provider_configs() result = None for provider_config in page.iterate_all(): if (provider_config.provider_id == saml_provider.provider_id): ...
class OptionSeriesAreasplineDataDragdropGuideboxDefault(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...
def pp_adv_phych_pdu(pdu: bytes, ch: int) -> list: header = pdu[:2] payload = pdu[2:] pdu_type = ((header[0] & PDU_TYPE_MSK) >> PDU_TYPE_POS) rfu = ((header[0] & RFU_MSK) >> RFU_POS) ch_sel = ((header[0] & CH_SEL_MSK) >> CH_SEL_POS) tx_add = ((header[0] & TX_ADD_MSK) >> TX_ADD_POS) rx_add = ...
def test_sac_trainer_splitting_rollouts(): sac = train_function(n_epochs=2, epoch_length=2, deterministic_eval=False, eval_repeats=1, distributed_env_cls=SequentialVectorEnv, split_rollouts_into_transitions=True) assert isinstance(sac, SAC) sac = train_function(n_epochs=2, epoch_length=2, deterministic_eval...
def get_exterior_code(codes_dependance: dict, pathfile: str, previous_file_name=None, classes: str=None, relative: bool=None, jitted_dicts: dict=None): special = [] treated = [] for (func, dep) in codes_dependance.items(): if (not dep): continue module_ext = extast.parse(dep) ...
class TabularEditor(BasicEditorFactory): klass = Property() show_titles = Bool(True) show_row_titles = Bool(False) update = Str() refresh = Str() auto_update = Bool(False) selected = Str() selected_row = Str() selectable = Bool(True) activated = Str() activated_row = Str() ...
class TestGraphApiTraceLoggingService(TestCase): def setUp(self) -> None: self.logger = mock.create_autospec(logging.Logger) self.mock_requests = mock.create_autospec(requests) self.mock_msg_queue = mock.create_autospec(SimpleQueue) self.mock_requests.exceptions = requests.exceptions...
class SidewaysShooter(): def __init__(self): pygame.init() self.clock = pygame.time.Clock() self.settings = Settings() self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption('Sideways Shooter') self....
def convert_inputs(model: Model, X_heads: Tuple[(Floats2d, Ints1d)], is_train: bool=False): (X, H) = X_heads Xt = xp2torch(X, requires_grad=is_train) Ht = xp2torch(H) def convert_from_torch_backward(d_inputs: ArgsKwargs) -> Tuple[(Floats2d, Ints1d)]: dX = cast(Floats2d, torch2xp(d_inputs.args[0]...
def mask_is_allowed(m, i): if (type(m) is list): assert all([((type(x) is int) or (type(x) is np.int64)) for x in m]), 'Sparse mask must be a list of int or np.int64' return (i in m) elif ((type(m) is int) or np.isscalar(m)): return (i == int(m)) return np.isclose(m[i], 0, atol=1e-08...
def test_forwarding_methods(solc_tester): foo = solc_tester.foo assert (foo(12, 13) == foo['uint,uint'](12, 13)) assert (foo.call(12, 13) == foo['uint,uint'].call(12, 13)) assert (foo.transact(12, 13).return_value == foo['uint,uint'].transact(12, 13).return_value) assert (foo.encode_input(12, 13) ==...
class OFPQueueStats(ofproto_parser.namedtuple('OFPQueueStats', ('port_no', 'queue_id', 'tx_bytes', 'tx_packets', 'tx_errors'))): def parser(cls, buf, offset): queue = struct.unpack_from(ofproto.OFP_QUEUE_STATS_PACK_STR, buf, offset) stats = cls(*queue) stats.length = ofproto.OFP_QUEUE_STATS_...
def make_stock_reconciliation(list_for_entry, date, cost_center): doc = frappe.new_doc('Stock Reconciliation') doc.purpose = 'Stock Reconciliation' doc.set_posting_time = 1 doc.posting_date = date doc.posting_time = '00:00:00' doc.cost_center = cost_center doc.set('items', []) doc.differ...
def get_dihedral_inds(coords3d, bond_inds, bend_inds, max_deg, logger=None): max_rad = np.deg2rad(max_deg) bond_dict = dict() for (from_, to_) in bond_inds: bond_dict.setdefault(from_, list()).append(to_) bond_dict.setdefault(to_, list()).append(from_) proper_dihedral_inds = list() i...
class OptionSeriesFunnel3dSonificationTracksMappingLowpassFrequency(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): ...
_op([AllocCursorA, ListA(OptionalA(NewExprA('buf_cursor'))), BoolA]) def bound_alloc(proc, buf_cursor, new_bounds, unsafe_disable_checks=False): stmt = buf_cursor._impl if (len(stmt._node.type.hi) != len(new_bounds)): raise ValueError(f'buffer has {len(stmt._node.type.hi)} dimensions, but only {len(new_...
class Module01(Digraph.Node): depends_on = [] def __init__(self, config): Digraph.Node.__init__(self, 'Module01') def get_type_set(self): return set([InputModuleTypes.reqdeps]) def set_modules(self, mods): pass def rewrite(self, reqset): return False
def _value_export_txt(run_path: Path, export_base_name: str, values: Mapping[(str, Mapping[(str, float)])]) -> None: path = (run_path / f'{export_base_name}.txt') _backup_if_existing(path) if (len(values) == 0): return with path.open('w') as f: for (key, param_map) in values.items(): ...
class Child(HasTraits): name = Str('child') age = Float(10.0) property = Instance(tvtk.Property, (), record=True) toy = Instance(Toy, record=True) friends = List(Str) def grow(self, x): self.age += x self.f(1) def f(self, args): return args def not_recordable(self...
class OptionSeriesTimelineDataAccessibility(Options): def description(self): return self._config_get(None) def description(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(None) def enabled(self, flag: bool): self._config(flag...
class ExpiredFilter(BooleanListFilter): title = _('Expired') parameter_name = 'expired' def queryset(self, request, queryset): if (self.value() == 'yes'): return queryset.expired().filter(expired=True) if (self.value() == 'no'): return queryset.expired().filter(expire...
class OptionSeriesSolidgaugeDatalabels(Options): def align(self): return self._config_get('center') def align(self, text: str): self._config(text, js_type=False) def allowOverlap(self): return self._config_get(False) def allowOverlap(self, flag: bool): self._config(flag, ...
.usefixtures('use_tmpdir') def test_gui_iter_num(monkeypatch, qtbot): config_file = Path('config.ert') config_file.write_text('NUM_REALIZATIONS 1\n', encoding='utf-8') args_mock = Mock() args_mock.config = str(config_file) def _assert_iter_in_args(panel): assert (panel.getSimulationArguments...
(context_settings=dict(ignore_unknown_options=True)) ('arguments', nargs=(- 1), type=click.UNPROCESSED) ('--coverage/--no-coverage', default=False) def test(coverage, arguments): os.environ['COPRS_ENVIRON_UNITTEST'] = '1' if (not (('COPR_CONFIG' in os.environ) and os.environ['COPR_CONFIG'])): os.environ...
def check_libusb(): logger.info('making sure libusb is installed') try: import usb.core except ImportError: logger.error('pyusb is not installed. Install script usually fails here on first attempt. Running it again should allow installation to complete.') raise try: usb.c...
class CloneTestCase(unittest.TestCase): def test_any(self): b = ClassWithAny() f = Foo() f.s = 'the f' b.x = f bc = b.clone_traits(traits='all', copy='deep') self.assertNotEqual(id(bc.x), id(f), 'Foo x not cloned') def test_instance(self): b = ClassWithIns...
def extractArchiveofmemoriesWordpressCom(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, ...
def boto_service_definition_files(): botocore_data_dir = resource_filename(Requirement.parse('botocore'), 'botocore/data') files = [os.path.join(dirname, file_in_dir) for (dirname, _, files_in_dir) in os.walk(botocore_data_dir) for file_in_dir in files_in_dir if fnmatch.fnmatch(file_in_dir, 'service-*.json.gz')...
class RowReferenceMixin(): def _allocate_(self): if (not self._refrecord): self._refrecord = self._refmeta.fetch(self) if (not self._refrecord): raise RuntimeError(('Using a recursive select but encountered a broken ' + ('reference: %s %r' % (self._table, self)))) def __g...
('cuda.gen_cutlass_ops') def gen_ops(arch, cuda_version, allow_cutlass_sm90, force_cutlass_sm90): import cutlass_lib args = Args(arch) if (cuda_version is not None): args.cuda_version = cuda_version manifest = cutlass_lib.manifest.Manifest(args) if (arch == '90'): if force_cutlass_sm...
def parse_qualname(value): if ((not value) or (not isinstance(value, str))): return (None, None, None) (location, sep, qualname) = value.rpartition(':') if (not is_valid_qualname(qualname)): return (None, None, None) if (not sep): return (qualname, None, None) if _looks_like_...
class meter_config_stats_reply(stats_reply): version = 5 type = 19 stats_type = 10 def __init__(self, xid=None, flags=None, entries=None): if (xid != None): self.xid = xid else: self.xid = None if (flags != None): self.flags = flags els...
def write_signature_clusters_vcf(working_dir, clusters, version): (deletion_signature_clusters, insertion_signature_clusters, inversion_signature_clusters, tandem_duplication_signature_clusters, insertion_from_signature_clusters, translocation_signature_clusters) = clusters if (not os.path.exists((working_dir +...
def MatrixMultiply(left, right): result = rl.ffi.new('struct Matrix *') result.m0 = ((((left.m0 * right.m0) + (left.m1 * right.m4)) + (left.m2 * right.m8)) + (left.m3 * right.m12)) result.m1 = ((((left.m0 * right.m1) + (left.m1 * right.m5)) + (left.m2 * right.m9)) + (left.m3 * right.m13)) result.m2 = ((...
def add_in_place(n: Node): if (n.kind == Kind.NO_INPUT): data_sources.nodes.append(n) elif (n.kind == Kind.DATA_MANIPULATION): data_manipulation.nodes.append(n) elif (n.kind == Kind.DATA_SAMPLING): data_sampling.nodes.append(n) elif (n.kind == Kind.DATA_TRANSFORMATION): d...
def map_erpnext_variant_to_shopify_variant(shopify_product: Product, erpnext_item, variant_attributes): variant_product_id = frappe.db.get_value('Ecommerce Item', {'erpnext_item_code': erpnext_item.name, 'integration': MODULE_NAME}, 'integration_item_code') if (not variant_product_id): for variant in sh...
class Window(): UP = (- 1) DOWN = 1 def __init__(self, stdscr, pages, titles): self.top = 0 self.position = self.top self.pages = pages self.page_titles = titles self.cur_page = 0 self.window = stdscr self.height = (curses.LINES - 1) self.width...
class OptionSeriesBubbleSonificationDefaultinstrumentoptionsMappingPitch(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): ...
class FaucetTaggedVLANPCPTest(FaucetTaggedTest): CONFIG_GLOBAL = '\nvlans:\n 100:\n description: "tagged"\nacls:\n 1:\n - rule:\n vlan_vid: 100\n vlan_pcp: 1\n actions:\n output:\n set_fields:\n - vlan_pcp:...
def load_csv(fstr, resample=None): df = pd.read_csv(fstr) def f(x): return re.sub('/', '-', x) timestr = df['timestmp'].map(f) icp_timestmp = pd.to_datetime(timestr) icp_data = df['p'].values ts = pd.Series(icp_data, index=icp_timestmp) if (resample is not None): ts = ts.resa...
class OptionPlotoptionsErrorbarSonificationContexttracksMapping(Options): def frequency(self) -> 'OptionPlotoptionsErrorbarSonificationContexttracksMappingFrequency': return self._config_sub_data('frequency', OptionPlotoptionsErrorbarSonificationContexttracksMappingFrequency) def gapBetweenNotes(self) -...
def decode_snooz_v2(decompressed, last_timestamp_ms): first_timestamp_ms = (last_timestamp_ms + ) offset = 0 while (offset < len(decompressed)): (length, packet_length, delta_time_ms, snooz_type) = struct.unpack_from('=HHIb', decompressed, offset) offset += ((9 + length) - 1) first_t...
() _and_sanitize_search_inputs def get_healthcare_service_units(doctype, txt, searchfield, start, page_len, filters): table = frappe.qb.DocType('Healthcare Service Unit') query = frappe.qb.from_(table).where((table.is_group == 0)).where((table.company == filters.get('company'))).where(table.name.like('%{0}%'.fo...
class SettingForm(forms.ModelForm): class Meta(): model = Setting fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if ('description' in self.fields): self.fields['description'].widget = forms.Textarea(attrs={'rows': 3, 'cols': ...
class OptionSeriesArcdiagramNodesDatalabelsFilter(Options): def operator(self): return self._config_get(None) def operator(self, value: Any): self._config(value, js_type=False) def property(self): return self._config_get(None) def property(self, text: str): self._config(t...
class ChrootsValidator(object): def __call__(self, form, field): if (not field.data): return selected = set(field.data.split()) enabled = set(MockChrootsLogic.active_names()) if (selected - enabled): raise wtforms.ValidationError('Such chroot is not available:...
class UnsupportedMorxLookupTest(unittest.TestCase): def __init__(self, methodName): unittest.TestCase.__init__(self, methodName) if (not hasattr(self, 'assertRaisesRegex')): self.assertRaisesRegex = self.assertRaisesRegexp def test_unsupportedLookupType(self): data = bytesjoi...
def ensure_charge_in_range(sample: Callable[([Union[(ArrayLike[float], SpatialDataArray)], Union[(ArrayLike[float], SpatialDataArray)]], Union[(ArrayLike[float], ArrayLike[Complex], SpatialDataArray)])]) -> Callable[([Union[(ArrayLike[float], SpatialDataArray)], Union[(ArrayLike[float], SpatialDataArray)]], Union[(Arra...
class ChatHistoryManager(): def __init__(self, chat_ctx: ChatContext, prompt_template: PromptTemplate, history_storage: BaseChatHistoryMemory, chat_retention_rounds: Optional[int]=0) -> None: self._chat_ctx = chat_ctx self.chat_retention_rounds = chat_retention_rounds self.current_message: O...
class TestNull(util.ColorAsserts, unittest.TestCase): def test_null_input(self): c = Color('hsi', [NaN, 0.5, 1], 1) self.assertTrue(c.is_nan('hue')) def test_none_input(self): c = Color('color(--hsi none 0% 75% / 1)') self.assertTrue(c.is_nan('hue')) def test_null_normalizati...
def test_bucket_sort_agg(): bucket_sort_agg = aggs.BucketSort(sort=[{'total_sales': {'order': 'desc'}}], size=3) assert (bucket_sort_agg.to_dict() == {'bucket_sort': {'sort': [{'total_sales': {'order': 'desc'}}], 'size': 3}}) a = aggs.DateHistogram(field='date', interval='month') a.bucket('total_sales',...
.parametrize('iin, jin, xcor, ycor, xinc, yinc, ncol, nrow, yflip, rota, exp_xori, exp_yori', [(0, 0, 0.0, 0.0, 50.0, 50.0, 2, 2, 1, 0.0, 0.0, 0.0), (0, 0, 0.0, 0.0, 50.0, 50.0, 2, 2, 1, 90.0, 0.0, 0.0), (0, 0, 100.0, 300.0, 50.0, 50.0, 2, 2, 1, 0.0, 100.0, 300.0), (1, 1, 100.0, 300.0, 50.0, 50.0, 2, 2, 1, 0.0, 50.0, 2...
def test_paramters_with_custom_init(): class Point(Record, include_metadata=False): x: int y: int def __init__(self, x, y, **kwargs): self.x = x self.y = y p = Point(30, 10) assert (p.x == 30) assert (p.y == 10) payload = p.dumps(serializer='json') ...
def test_error_handler_after_processor_error(app, client): app.testing = False _request def before_request(): if (_trigger == 'before'): (1 // 0) _request def after_request(response): if (_trigger == 'after'): (1 // 0) return response ('/') def...
class TargetingGeoLocationLocationExpansion(AbstractObject): def __init__(self, api=None): super(TargetingGeoLocationLocationExpansion, self).__init__() self._isTargetingGeoLocationLocationExpansion = True self._api = api class Field(AbstractObject.Field): allowed = 'allowed' ...
def deform_to_native(native_mesh, dest_mesh, dscalars, expected_labels, subject_id, sphere='sphere', scale=2.5): resample_surfs_and_add_to_spec(subject_id, native_mesh, dest_mesh, current_sphere=sphere) make_inflated_surfaces(subject_id, dest_mesh, iterations_scale=scale) resample_metric_and_label(subject_i...
_converter(acc_ops.permute) def acc_ops_permute(target: Target, args: Tuple[(Argument, ...)], kwargs: Dict[(str, Argument)], name: str) -> ConverterOutput: input_val = kwargs['input'] if (not isinstance(input_val, AITTensor)): raise ValueError(f'Unexpected input for {name}: {input_val}') permutation...
def scatter_optimizer_state_dict(optimizer, optim_state_dict, model: FSDPWrapper): if (model.load_state_dict_type == StateDictType.FULL_STATE_DICT): optim_state_dict = FSDP.shard_full_optim_state_dict(optim_state_dict, model, optim=optimizer) elif (model.load_state_dict_type == StateDictType.SHARDED_STA...
def generate_password_based_auth_token(asset_name, fledge_url): conn = conn.request('POST', '/fledge/login', json.dumps({'username': 'user', 'password': 'fledge'})) r = conn.getresponse() assert (200 == r.status) r = r.read().decode() jdoc = json.loads(r) assert (LOGIN_SUCCESS_MSG == jdoc['...
class CRawEye(ctypes.Structure): _fields_ = [('eyeballPosX', ctypes.c_double), ('eyeballPosY', ctypes.c_double), ('eyeballPosZ', ctypes.c_double), ('eyeballConfidence', ctypes.c_double), ('gazeVectorX', ctypes.c_double), ('gazeVectorY', ctypes.c_double), ('gazeVectorZ', ctypes.c_double), ('gazeVectorConfidence', ct...
def test_wf_docstring(): model_wf = get_serializable(OrderedDict(), serialization_settings, my_wf_example) assert (len(model_wf.template.interface.outputs) == 2) assert (model_wf.template.interface.outputs['o0'].description == 'outputs') assert (model_wf.template.interface.outputs['o1'].description == '...
def _check_if_user_can_edit_copr(ownername, projectname): copr = get_copr(ownername, projectname) if (not flask.g.user.can_edit(copr)): raise AccessRestricted("User '{0}' can not see permissions for project '{1}' (missing admin rights)".format(flask.g.user.name, '/'.join([ownername, projectname]))) ...
class CustomFontEditor(Editor): def init(self, parent): self.control = panel = TraitsUIPanel(parent, (- 1)) sizer = wx.BoxSizer(wx.VERTICAL) sizer2 = wx.BoxSizer(wx.HORIZONTAL) facenames = self.factory.all_facenames() control = self._facename = wx.Choice(panel, (- 1), wx.Poin...
class OptionPlotoptionsArearangeSonificationTracksMappingTremolo(Options): def depth(self) -> 'OptionPlotoptionsArearangeSonificationTracksMappingTremoloDepth': return self._config_sub_data('depth', OptionPlotoptionsArearangeSonificationTracksMappingTremoloDepth) def speed(self) -> 'OptionPlotoptionsAre...
class ReplaygainLimiter(ElementBin): index = 80 name = 'rglimiter' def __init__(self): ElementBin.__init__(self, name=self.name) self.rglimit = Gst.ElementFactory.make('rglimiter', None) self.elements[50] = self.rglimit self.audioconvert = Gst.ElementFactory.make('audioconver...
def test_bytearray(use_builtin_types): DataClass = (bytes if use_builtin_types else plistlib.Data) pl = DataClass(b'<binary gunk\x00\x01\x02\x03>') array = (bytearray(pl) if use_builtin_types else bytearray(pl.data)) data = plistlib.dumps(array) pl2 = plistlib.loads(data, use_builtin_types=use_built...
def get_contract_names(full_source: str) -> List: comment_regex = '(?:\\s*\\/\\/[^\\n]*)|(?:\\/\\*[\\s\\S]*?\\*\\/)' uncommented_source = re.sub(comment_regex, '', full_source) contracts = re.findall('((?:abstract contract|contract|library|interface)\\s[^;{]*{[\\s\\S]*?})\\s*(?=(?:abstract contract|contract...
_op([GapCursorA, PosIntA, BoolA]) def fission(proc, gap_cursor, n_lifts=1, unsafe_disable_checks=False): if (gap_cursor.type() == ic.GapType.Before): stmt = gap_cursor.anchor().prev() else: stmt = gap_cursor.anchor() if ((not stmt) or (not stmt.next())): raise ValueError('expected cu...
class TestExamples(unittest.TestCase): def test_random(self): print('\ntest random:') with using(random_data): results = call_bbopt(random_file, procs=1) want = max(get_nums(results, numtype=int)) assert os.path.exists(random_data) from bbopt.examples ...
class TestActionFileAllocation(CuratorTestCase): def test_include(self): alloc = 'include' self.write_config(self.args['configfile'], testvars.client_config.format(HOST)) self.write_config(self.args['actionfile'], testvars.allocation_test.format(KEY, VALUE, alloc, False)) (idx1, idx2...
def set_verified(verifying_client: VerifyingClient) -> VerificationsModel: with session() as s: expires = (now() + VERIFICATION_DURATION) vid = verifying_client.verification_id ip4 = verifying_client.ip4 model = VerificationsModel.from_id_ip4_expires(vid, ip4, expires) orm_mo...
def _get_filetype_parser(file_path, parser_type): filetype_handlers = {'json': {'string': _parse_json_string, 'file': _parse_json_file}, 'yaml': {'string': _parse_yaml, 'file': _parse_yaml}} file_ext = file_path.split('.')[(- 1)] if (file_ext not in filetype_handlers): raise util_errors.InvalidFileE...
class TestActionFileSnapshot(CuratorTestCase): def test_snapshot(self): self.create_indices(5) self.create_repository() snap_name = 'snapshot1' self.write_config(self.args['configfile'], testvars.client_config.format(HOST)) self.write_config(self.args['actionfile'], testvars....
class PlaylistExportDialog(FileOperationDialog): __gsignals__ = {'message': (GObject.SignalFlags.RUN_LAST, GObject.TYPE_BOOLEAN, (Gtk.MessageType, GObject.TYPE_STRING), GObject.signal_accumulator_true_handled)} def __init__(self, playlist, parent=None): FileOperationDialog.__init__(self, title=_('Export...
def commands(): import os unsetenv('PYTHONHOME') env.CGRU_LOCATION.set('/opt/cgru-{}.{}.{}'.format(env.REZ_CGRU_MAJOR_VERSION, env.REZ_CGRU_MINOR_VERSION, env.REZ_CGRU_PATCH_VERSION)) env.PATH.prepend('${CGRU_LOCATION}/bin') env.PATH.prepend('${CGRU_LOCATION}/software_setup/bin') env.CGRU_PYTHON...
class TestSuperFencesCustomDefault(util.MdCase): extension = ['pymdownx.superfences'] extension_configs = {'pymdownx.superfences': {'custom_fences': [{'name': '*', 'class': '', 'format': default_format}, {'name': 'math', 'class': 'arithmatex', 'format': arithmatex.arithmatex_fenced_format(mode='generic')}]}} ...
class KLDivergence(): def __init__(self, epsilon: float=1e-10): self.epsilon = epsilon def __call__(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor: y_pred = convert_to_tensor(y_pred) y_true = convert_to_tensor(y_true) check_same_shape(y_pred, y_true) y_...
class OptionPlotoptionsPolygonSonificationContexttracksMappingLowpassFrequency(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:...
def test_records_stats(): env = build_dummy_maze_env() env = LogStatsWrapper.wrap(env) env.reset() for i in range(5): env.step(env.action_space.sample()) env.write_epoch_stats() assert (env.get_stats_value(RewardEvents.reward_original, LogStatsLevel.EPOCH, name='total_step_count') == 5) ...
def edit_catfruit(save_stats: dict[(str, Any)]) -> dict[(str, Any)]: max_cf = 128 if (save_stats['game_version']['Value'] >= 110400): max_cf = None catfruit = item.IntItemGroup.from_lists(names=get_fruit_names(helper.check_data_is_jp(save_stats)), values=save_stats['cat_fruit'], maxes=max_cf, group_...
class InstagramShoppingMerchantReviewMessage(AbstractObject): def __init__(self, api=None): super(InstagramShoppingMerchantReviewMessage, self).__init__() self._isInstagramShoppingMerchantReviewMessage = True self._api = api class Field(AbstractObject.Field): help_url = 'help_url...
class TestDevice(object): def mouse(self): settings = mouse_settings.FakeMouseSettings(4152, 47789, prime_wireless_wired.profile) return mouse.Mouse(usbhid.FakeDevice(), prime_wireless_wired.profile, settings) .parametrize('value,expected_hid_report', [(100, b'\x02\x00-\x01\x00\x00'), (200, b'\x...
class OptionSeriesTimelineSonificationTracksPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): sel...
def extract96RoryWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Jikuu Mahou', 'Jikuu Mahou de Isekai to Chikyuu wo Ittarikitari', 'translated'), ('PRC', 'PRC', 't...
class OptionSeriesBellcurveDragdropGuideboxDefault(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(self...
def test_clean_up_ast(): asgraph = AbstractSyntaxInterface() code_node_1 = asgraph._add_code_node([Assignment(var('u'), const(9))]) code_node_2 = asgraph._add_code_node([Break()]) code_node_3 = asgraph._add_code_node([Assignment(var('v'), const(9))]) root_seq_node = asgraph.factory.create_seq_node()...
class BeamSyncer(Service): def __init__(self, chain: AsyncChainAPI, db: AtomicDatabaseAPI, chain_db: BaseAsyncChainDB, peer_pool: ETHPeerPool, event_bus: EndpointAPI, metrics_registry: MetricsRegistry, checkpoint: Checkpoint=None, force_beam_block_number: BlockNumber=None, enable_backfill: bool=True, enable_state_b...
class Dnf(Backend): def updates(self): if HAS_DNF_BINDINGS: try: with dnf.Base() as base: base.read_all_repos() base.fill_sack() upgrades = base.sack.query().upgrades().run() notif_body = ''.join([('%s: %...
class Keybindings(Options): def addRow(self, keys): self.component.extendModule('keybindings', 'actions', 'addRow', 'function(event){event.preventDefault(); this.table.addRow()}') self._attrs['addRow'] = keys return self def deleteSelectedRows(self, keys): self.component.extendMo...
class StreamStream(_MultiCallable, grpc.StreamStreamMultiCallable): def __call__(self, request_iterator, timeout=None, metadata=None, *args, **kwargs): with _disable_close_old_connections(): context = FakeContext() context._invocation_metadata.extend((metadata or [])) ret...
class TestDownload(unittest.TestCase): _filename = (('facebook_' + uuid.uuid4().hex) + '.html') def run(self, result=None): with patch('iopath.common.event_logger.EventLogger.log_event'): super(TestDownload, self).run(result) def test_download(self) -> None: download(' '.', filen...
class FaucetUntaggedHairpinTest(FaucetUntaggedTest): NETNS = True CONFIG = '\n interfaces:\n %(port_1)d:\n hairpin: True\n native_vlan: 100\n %(port_2)d:\n native_vlan: 100\n %(port_3)d:\n native_vlan: 100\n ...
def extractAsterlislockedseriesWordpressCom(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, nam...
def test_deterministic_hash(tmp_path): workflows_dir = (tmp_path / 'workflows') workflows_dir.mkdir() open((workflows_dir / '__init__.py'), 'a').close() workflow_file = (workflows_dir / 'hello_world.py') workflow_file.write_text(MAIN_WORKFLOW) imperative_workflow_file = (workflows_dir / 'imperat...
class ReqType(ReqTagGeneric): types = [['master requirement', RequirementType.master_requirement], ['initial requirement', RequirementType.initial_requirement], ['design decision', RequirementType.design_decision], ['requirement', RequirementType.requirement]] def __init__(self, config): ReqTagGeneric._...
def encode_branch_node(left_child_node_hash, right_child_node_hash): validate_is_bytes(left_child_node_hash) validate_length(left_child_node_hash, 32) validate_is_bytes(right_child_node_hash) validate_length(right_child_node_hash, 32) return ((BRANCH_TYPE_PREFIX + left_child_node_hash) + right_child...
class OptionPlotoptionsGaugeSonificationDefaultspeechoptionsPointgrouping(Options): def algorithm(self): return self._config_get('last') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: bool...
class OptionPlotoptionsSeriesSonificationContexttracksMappingTremoloSpeed(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 fontawesome_role(role, rawtext, text, lineno, inliner, options={}, content=[]): try: (args, kwargs) = string_to_func_inputs(text) node = create_fa_node(*args, **kwargs) except Exception as err: msg = inliner.reporter.error(f'FontAwesome input is invalid: {err}', line=lineno) ...