code
stringlengths
281
23.7M
def write_audacity_labels(dst_path, labels): with open(dst_path, 'w') as of: for (s, e, l) in labels: (s, e) = ((s * 1e-07), (e * 1e-07)) if (('-' in l) and ('+' in l)): ph = l.split('-')[1].split('+')[0] else: ph = l of.write('...
def patch_game_name_and_id(game_files_path: Path, new_name: str, publisher_id: str): b = new_name.encode('ASCII') if (len(b) > 40): raise ValueError(f"Name '{new_name}' is bigger than 40 bytes") b = (b + (b'\x00' * (40 - len(b)))) pid = publisher_id.encode('ASCII') if (len(pid) != 2): ...
def readable(tag, plural=False): try: if (tag[0] == '~'): if (tag[1] == '#'): tag = tag[2:] else: tag = tag[1:] except IndexError: return ngettext('Invalid tag', 'Invalid tags', 1) def desc(tag): if plural: plural_de...
class TestDataID(unittest.TestCase): def test_basic_init(self): from satpy.dataset.dataid import DataID from satpy.dataset.dataid import default_id_keys_config as dikc from satpy.dataset.dataid import minimal_default_keys_config as mdkc did = DataID(dikc, name='a') assert (di...
_menu('Selection to IPython', menu='IPython') def set_selection_in_ipython(*args): try: if ((not getattr(sys, '_ipython_app', None)) or (not sys._ipython_kernel_running)): raise Exception('IPython kernel not running') xl = xl_app(com_package='win32com') selection = xl.Selection ...
class ProxyPLoss(nn.Module): def __init__(self, num_classes, scale): super(ProxyPLoss, self).__init__() self.soft_plus = nn.Softplus() self.label = torch.LongTensor([i for i in range(num_classes)]) self.scale = scale def forward(self, feature, target, proxy): feature = F....
class TestEvaluate(BaseTestCase): async def test_evaluate(self): result = (await self.page.evaluate('() => 7 * 3')) self.assertEqual(result, 21) async def test_await_promise(self): result = (await self.page.evaluate('() => Promise.resolve(8 * 7)')) self.assertEqual(result, 56) ...
class CapacitorViewFull(StatsView): name = 'capacitorViewFull' def __init__(self, parent): StatsView.__init__(self) self.parent = parent def getHeaderText(self, fit): return _t('Capacitor') def getTextExtentW(self, text): (width, height) = self.parent.GetTextExtent(text) ...
def get_comp_grnd_probs(model, pointer_logprobs, step_history, grounding): assert (len(model.ids_to_grounding_choices) == len(pointer_logprobs)) keep_pointer_logprobs = [] refs = [idx for (rule, idx) in step_history if (rule == 'ref')] assert (len(refs) == 2), refs is_filter = (refs[0] == refs[1]) ...
def test_parse_tree(): problem = '(q-transform/hint (quote (lambda (cdr (cdr (var ()))))) (quote ((() y . 1) (#f y () . #t) (#f b () b . y) (x #f (#f . #f) . #t) (a #f y x s . a))))' step = 0 print('Starting problem:', problem) with Interaction(lisp.parse(problem)) as env: signal = None ...
def tensor2imgs(tensor, mean=(0, 0, 0), std=(1, 1, 1), to_rgb=True): num_imgs = tensor.size(0) mean = np.array(mean, dtype=np.float32) std = np.array(std, dtype=np.float32) imgs = [] for img_id in range(num_imgs): img = tensor[(img_id, ...)].cpu().numpy().transpose(1, 2, 0) img = mmc...
((enum is None), 'enum is not available') class TestNestedStateEnums(TestEnumsAsStates): def setUp(self): super(TestNestedStateEnums, self).setUp() self.machine_cls = HierarchicalMachine def test_root_enums(self): states = [self.States.RED, self.States.YELLOW, {'name': self.States.GREEN,...
class BridgeTowerVisionConfig(PretrainedConfig): model_type = 'bridgetower_vision_model' def __init__(self, hidden_size=768, num_hidden_layers=12, num_channels=3, patch_size=16, image_size=288, initializer_factor=1, layer_norm_eps=1e-05, stop_gradient=False, share_layernorm=True, remove_last_layer=False, **kwar...
class CalculatorForm(Form): def __init__(self, view): super().__init__(view, 'dynamic_content_error_form') self.use_layout(FormLayout()) self.calculator = Calculator.for_current_session() try: self.enable_refresh(on_refresh=self.calculator.events.inputs_changed) e...
def put_html(html: Any, sanitize: bool=False, scope: str=None, position: int=OutputPosition.BOTTOM) -> Output: if hasattr(html, '__html__'): html = html.__html__() elif hasattr(html, '_repr_html_'): html = html._repr_html_() spec = _get_output_spec('html', content=html, sanitize=sanitize, sc...
def _inner_fmt(k: str, v: Any, table: TableFmt) -> Iterator[str]: quote_function = table.get('quote', (lambda a: a)) if isinstance(v, list): for inner_v in v: qv = quote_function(inner_v) (yield table['item'].format(k=k, v=qv)) else: qv = quote_function(v) (yi...
class ClientGenerator(BaseGenerator): def __init__(self, keep_sync: Optional[List[str]]=None, class_replace_map: Optional[Dict[(str, str)]]=None, import_replace_map: Optional[Dict[(str, str)]]=None, exclude_methods: Optional[List[str]]=None): super().__init__() self._async_methods: Optional[List[str...
class TestUTCDateTimeAttribute(): def setup_method(self): self.attr = UTCDateTimeAttribute() self.dt = datetime(2047, 1, 6, 8, 21, 30, 2000, tzinfo=timezone.utc) def test_utc_datetime_attribute(self): attr = UTCDateTimeAttribute(default=self.dt) assert (attr.attr_type == STRING) ...
('beeref.selection.SelectableMixin.mousePressEvent') def test_mouse_press_event_when_leftclick(mouse_mock): item = MultiSelectItem() item.fit_selection_area(QtCore.QRectF(0, 0, 100, 80)) event = MagicMock(button=MagicMock(return_value=Qt.MouseButton.LeftButton)) item.mousePressEvent(event) event.ign...
class TestMWSResponseObject(): def test_mwsresponse_repr(self, simple_mwsresponse): assert (repr(simple_mwsresponse) == '<MWSResponse [200]>') def test_mwsresponse_base_attrs(self, simple_mwsresponse): mws_response = simple_mwsresponse assert isinstance(mws_response.original, Response) ...
def main(): utils.change_cwd() out_filename = 'misc/file_version_info.txt' filevers = (qutebrowser.__version_info__ + (0,)) prodvers = (qutebrowser.__version_info__ + (0,)) str_filevers = qutebrowser.__version__ str_prodvers = qutebrowser.__version__ comment_text = qutebrowser.__doc__ co...
('--update', is_flag=True, help='Update shared modules everywhere?', default=False) ('--status', is_flag=True, help='Show status of shared modules everywhere.', default=False) ('--delete', is_flag=True, help='Delete shared modules everywhere?', default=False) _commands.command(name='git-submodule') def git_submodule(up...
class MixedNonTagRefTest(models.Model): name = models.CharField(max_length=10) singletag = tagulous.models.SingleTagField(MixedNonTagModel, blank=True, related_name='singletags') tags = tagulous.models.TagField(MixedNonTagModel, blank=True, related_name='tags') fk = models.ForeignKey(MixedNonTagModel, b...
def test_reduce_concatenations() -> None: assert (str(parse('aa').reduce()) == 'a{2}') assert (str(parse('bb').reduce()) == 'b{2}') assert (str(parse('b*b').reduce()) == 'b+') assert (str(parse('aa{2,}').reduce()) == 'a{3,}') assert (str(parse('a*a{2}').reduce()) == 'a{2,}') assert (str(parse('a...
def test_to_recap_decimal(): converter = AvroConverter() avro_schema = {'type': 'record', 'name': 'test_decimal', 'fields': [{'name': 'decimal', 'type': {'type': 'bytes', 'logicalType': 'decimal', 'precision': 5, 'scale': 2}}]} schema = converter.to_recap(json.dumps(avro_schema)) field = schema.fields[0...
def uccsd_generator(single_amplitudes, double_amplitudes, anti_hermitian=True): generator = FermionOperator() if (isinstance(single_amplitudes, numpy.ndarray) or isinstance(double_amplitudes, numpy.ndarray)): (single_amplitudes, double_amplitudes) = uccsd_convert_amplitude_format(single_amplitudes, doub...
def is_duplicate_mapping(mapping: list[int], actual_types: list[Type], actual_kinds: list[ArgKind]) -> bool: return ((len(mapping) > 1) and (not ((len(mapping) == 2) and (actual_kinds[mapping[0]] == nodes.ARG_STAR) and (actual_kinds[mapping[1]] == nodes.ARG_STAR2))) and (not all((((actual_kinds[m] == nodes.ARG_STAR...
class RustLexer(RegexLexer): name = 'Rust' url = ' filenames = ['*.rs', '*.rs.in'] aliases = ['rust', 'rs'] mimetypes = ['text/rust', 'text/x-rust'] version_added = '1.6' keyword_types = (words(('u8', 'u16', 'u32', 'u64', 'u128', 'i8', 'i16', 'i32', 'i64', 'i128', 'usize', 'isize', 'f32', 'f...
def plot_rat_stats(rat_sim, save_root, fmt): for rating in range(1, 6): exp_sim = (rat_sim == rating).astype(np.int32) name = 'rat_stats_{}.{}'.format(rating, fmt) title = 'Item Rating {} Distribution'.format(rating) plot_exp_stats(exp_sim, save_root, fmt, name, title)
class MenuButton(TelegramObject): __slots__ = ('type',) def __init__(self, type: str, *, api_kwargs: Optional[JSONDict]=None): super().__init__(api_kwargs=api_kwargs) self.type: str = type self._id_attrs = (self.type,) self._freeze() def de_json(cls, data: Optional[JSONDict],...
def RunGUI(sdkpath, args): root = tk.Tk() style = ttk.Style(root) style.theme_use('default') ttk.Style().configure('TButton', padding=6, relief='groove', border=2, foreground=GetButtonTextColour(), background=GetButtonBackground()) ttk.Style().configure('TLabel', foreground=GetTextColour(), backgrou...
class CallBackVerification(object): def __init__(self, val_targets, rec_prefix, summary_writer=None, image_size=(112, 112)): self.rank: int = distributed.get_rank() self.highest_acc: float = 0.0 self.highest_acc_list: List[float] = ([0.0] * len(val_targets)) self.ver_list: List[objec...
def attr_parse(stream, length, attr_type_cls): values = collections.OrderedDict() while (length > 0): (attr_type, value) = struct.unpack('>HH', stream.read(4)) length -= 4 if (attr_type & 32768): attr_type &= 32767 else: length -= value value =...
class ValidationCallback(Callback): def __init__(self, manager: Manager, summary_writer: SummaryWriter, args, training_state: 'TrainingState', last_model_path, validation_frequency): super().__init__() self._args = args self._validation_frequency = validation_frequency self._training...
def test_geodesic_inv__string_init(scalar_and_array): geod = Geod('+ellps=clrk66') (az12, az21, dist) = geod.inv(scalar_and_array(_BOSTON_LON), scalar_and_array(_BOSTON_LAT), scalar_and_array(_PORTLAND_LON), scalar_and_array(_PORTLAND_LAT)) assert_almost_equal((az12, az21, dist), (scalar_and_array((- 66.531...
def _expand_shape_to_4d(weight_tensor: libpymo.TensorParams): dims = len(weight_tensor.shape) if (dims > 5): raise RuntimeError if (dims == 4): (yield weight_tensor) else: orig_shape = weight_tensor.shape if (dims < 4): _4d_shape = np.append(orig_shape, [1 for...
def get_version_and_doc(filename): NS = dict(__version__='', __doc__='') docStatus = 0 with open(filename, 'rb') as fd: data = fd.read() for line in data.decode().splitlines(): if line.startswith('__version__'): exec(line.strip(), NS, NS) elif line.startswith('"""'): ...
def recover_coef1(seed): input_list = ['m', 'k', 'A0', 'c'] output_coef = 'm_coef' D_in = np.mat('1, 0, 0; 1, 0, -2; 0, 1, 0; 1, 0, -1').T D_out = np.mat('0;, 0; 1') dimension_info = [D_in, D_out] basis1_in = np.array([1, 1, 0, (- 2)]).reshape((- 1), 1) basis2_in = np.array([1, 0, 0, (- 1)])...
class Effect6600(BaseEffect): type = 'passive' def handler(fit, src, context, projectionRange, **kwargs): fit.ship.boostItemAttr('shieldThermalDamageResonance', src.getModifiedItemAttr('shipBonusCarrierC1'), skill='Caldari Carrier', **kwargs) fit.ship.boostItemAttr('shieldEmDamageResonance', src...
class TestReadmeSample(QiskitMLTestCase): def test_readme_sample(self): def print(*args): if args: self.log.debug(args[0], *args[1:]) from qiskit import BasicAer from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.aqua.algorithms import VQC ...
_config def test_maximize_with_move_to_screen(manager): manager.test_window('one') manager.c.window.toggle_maximize() assert (manager.c.window.info()['width'] == 464) assert (manager.c.window.info()['height'] == 316) assert (manager.c.window.info()['x'] == 16) assert (manager.c.window.info()['y'...
def get_matching_convtransp(conv_op: Type[_ConvNd]=None, dimension: int=None) -> Type[_ConvTransposeNd]: assert (not ((conv_op is not None) and (dimension is not None))), 'You MUST set EITHER conv_op OR dimension. Do not set both!' if (conv_op is not None): dimension = convert_conv_op_to_dim(conv_op) ...
def train(epoch, criterion_list, optimizer): train_loss = AverageMeter('train_loss', ':.4e') train_loss_cls = AverageMeter('train_loss_cls', ':.4e') train_loss_div = AverageMeter('train_loss_div', ':.4e') top1_num = 0 top5_num = 0 total = 0 if (epoch >= args.warmup_epoch): lr = adjus...
def _create_method_tolerance_ap_values(tolerance_ap_data_frame, method, ordered_class_names: List[str]): method_tolerance_ap_data_frame = tolerance_ap_data_frame[(tolerance_ap_data_frame[METHOD] == method)] return [method_tolerance_ap_data_frame[(method_tolerance_ap_data_frame[SpottingEvaluation.CLASS_NAME] == ...
class HSTPIPIER(IntEnum): RXINES = (1 << 0) TXOUTES = (1 << 1) TXSTPES = (1 << 2) UNDERFIES = (1 << 2) PERRES = (1 << 3) NAKEDES = (1 << 4) OVERFIES = (1 << 5) RXSTALLDES = (1 << 6) CRCERRES = (1 << 6) SHORTPACKETIES = (1 << 7) NBUSYBKES = (1 << 12) PDISHDMAS = (1 << 16) ...
def init_network_weights(model, init_type='normal', gain=0.02): def _init_func(m): classname = m.__class__.__name__ if (hasattr(m, 'weight') and ((classname.find('Conv') != (- 1)) or (classname.find('Linear') != (- 1)))): if (init_type == 'normal'): nn.init.normal_(m.weig...
def create_access_token(repo, role, kind=None, friendly_name=None): role = Role.get((Role.name == role)) kind_ref = None if (kind is not None): kind_ref = AccessTokenKind.get((AccessTokenKind.name == kind)) new_token = AccessToken.create(repository=repo, temporary=True, role=role, kind=kind_ref,...
def _dump_test(unit, test_type, test_files, timeout, test_dir, custom_deps, test_data, python_paths, split_factor, fork_mode, test_size, tags, requirements, binary_path='', old_pytest=False, test_cwd=None): if (test_type == 'PY_TEST'): script_rel_path = 'py.test' elif (test_type == 'FLEUR'): scr...
class _DebuggingTips(SetuptoolsWarning): _SUMMARY = 'Problem in editable installation.' _DETAILS = '\n An error happened while installing `{project}` in editable mode.\n\n The following steps are recommended to help debug this problem:\n\n - Try to install the project normally, without using the editab...
_funcify.register(ptr.RandomVariable) def jax_funcify_RandomVariable(op, node, **kwargs): rv = node.outputs[1] out_dtype = rv.type.dtype out_size = rv.type.shape if (op.ndim_supp > 0): out_size = node.outputs[1].type.shape[:(- op.ndim_supp)] if (None in out_size): assert_size_argumen...
def test_direct_junction_offsets_suc_suc_2_left(direct_junction_left_lane_fixture): (main_road, small_road, junction_creator) = direct_junction_left_lane_fixture main_road.add_successor(xodr.ElementType.junction, junction_creator.id) small_road.add_successor(xodr.ElementType.junction, junction_creator.id) ...
class MPRIS(EventPlugin): PLUGIN_ID = 'mpris' PLUGIN_NAME = _('MPRIS D-Bus Support') PLUGIN_DESC_MARKUP = _('Allows control of Quod Libet using the <a href=" 2</a> D-Bus Interface Specification. This allows various Linux desktop integrations (e.g. multimedia keys).') PLUGIN_ICON = Icons.NETWORK_WORKGROU...
class KnownValues(unittest.TestCase): def test_ea_adc2_k(self): (e, v, p, x) = kadc.kernel(nroots=3, kptlist=[0]) self.assertAlmostEqual(e[0][0], 0., 4) self.assertAlmostEqual(e[0][1], 1., 4) self.assertAlmostEqual(e[0][2], 1., 4) self.assertAlmostEqual(p[0][0], 1., 4) ...
def _sanitize_args_with_chunks(*args): new_args = [] for arg in args: if (_is_chunk_tuple(arg) and _chunks_are_irregular(arg)): new_chunks = _regular_chunks_from_irregular_chunks(arg) new_args.append(new_chunks) else: new_args.append(arg) return new_args
def test_invalid_coverage_source(testdir): script = testdir.makepyfile(SCRIPT) testdir.makeini('\n [pytest]\n console_output_style=classic\n ') result = testdir.runpytest('-v', '--cov=non_existent_module', '--cov-report=term-missing', script) result.stdout.fnmatch_lines(['*10 passed*'])...
def test_pytest() -> None: ast_node = builder.extract_node('\n import pytest\n pytest #\n ') module = next(ast_node.infer()) attrs = ['deprecated_call', 'warns', 'exit', 'fail', 'skip', 'importorskip', 'xfail', 'mark', 'raises', 'freeze_includes', 'set_trace', 'fixture', 'yield_fixture'] for at...
class TFBaseModelOutputWithPastAndCrossAttentions(ModelOutput): last_hidden_state: tf.Tensor = None past_key_values: Optional[List[tf.Tensor]] = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None cross_attentions: Optional[Tuple[tf.Tensor]] = None
def generate_model_output_with_no_positive_examples() -> Dict[(str, torch._tensor.Tensor)]: return {'predictions': torch.tensor([[1.0, 0.0, 0.51, 0.8, 1.0, 0.0, 0.51, 0.8, 1.0, 0.0, 0.51, 0.8]]), 'session': torch.tensor([[1, 1, 1, 1, 1, 1, 1, (- 1), (- 1), (- 1), (- 1), (- 1)]]), 'labels': torch.tensor([([0.0] * 12...
def select_best2(acc_dict, sess): sess_all_acc = acc_dict[str(sess)] f = 0 best_e = (len(sess_all_acc) - 1) for (e, pr) in enumerate(sess_all_acc): if ((pr[0] < pr[1]) and (f == 0)): best_base = pr[0] best_novel = pr[1] best_e = e f = 1 if ...
class TimeGraph(): def setup(self): test_file_path = mm.datasets.get_path('bubenec') self.df_streets = gpd.read_file(test_file_path, layer='streets') self.network = mm.gdf_to_nx(self.df_streets) self.network = mm.node_degree(self.network) self.dual = mm.gdf_to_nx(self.df_stre...
def parse_data(in_file='../../data/GYAFC/em/trn.tsv'): with open(in_file, 'r') as f: data = f.read().split('\n') data.remove('') contexted = [] for (i, line) in enumerate(data): source_txt = line.split('\t')[0] target_txt = line.split('\t')[1] row = (i, source_txt, ta...
class Effect5125(BaseEffect): type = 'passive' def handler(fit, src, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Remote Armor Repair Systems')), 'armorDamageAmount', src.getModifiedItemAttr('shipBonusGC2'), skill='Gallente Cruiser', **kwargs)
def get_ibnbresnet(blocks, model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs): if (blocks == 50): layers = [3, 4, 6, 3] elif (blocks == 101): layers = [3, 4, 23, 3] elif (blocks == 152): layers = [3, 8, 36, 3] else: raise ValueError('...
def pdf_a(x, p, m): scalar = False if (not hasattr(x, '__len__')): scalar = True x = np.asarray([x]) pr = np.array([((pdf_a_single_angle(xi, p, m, alpha) + pdf_a_single_angle(xi, p, m, beta)) if (xi not in [0, 1]) else pdf_a_single_angle(xi, p, m, alpha)) for xi in x]).flatten() return (...
class RedHatUserApi(object): def __init__(self, app_config): self.cert = (MARKETPLACE_FILE, MARKETPLACE_SECRET) self.user_endpoint = app_config.get('ENTITLEMENT_RECONCILIATION_USER_ENDPOINT') def get_account_number(self, user): email = user.email account_number = entitlements.get...
class Jfif(Jpeg): def from_stream(cls, stream): markers = _JfifMarkers.from_stream(stream) px_width = markers.sof.px_width px_height = markers.sof.px_height horz_dpi = markers.app0.horz_dpi vert_dpi = markers.app0.vert_dpi return cls(px_width, px_height, horz_dpi, ver...
def test_skipif_has_precendence_over_ancestor_failed(runner, tmp_path): source = '\n from pathlib import Path\n import pytask\n\n def task_example(produces=Path("file.txt")):\n raise Exception\n\n .skipif(True, reason="God knows.")\n def task_example_2(path=Path("file.txt")): ...\n ' tm...
class Gen_Data_loader(): def __init__(self, batch_size): self.batch_size = batch_size self.token_stream = [] def create_batches(self, data_file): self.token_stream = [] with open(data_file, 'r') as f: for line in f: line = line.strip().split() ...
class uvm_nonblocking_peek_port(uvm_port_base): def try_peek(self): try: (success, data) = self.export.try_peek() except AttributeError: raise UVMTLMConnectionError(f'Missing or wrong export in {self.get_full_name()}. Did you connect it?') return (success, data) d...
class TestMulticomp(TestCase): def test_fdr(self): (reject, pval_corr) = fdr(pvals) assert_array_equal(reject, [False, False, True, False, False]) assert_array_almost_equal(pval_corr, [0.52, 0.175, 0.0005, 0.075, 0.175]) (_, pval_corr) = fdr(pvals2_NA) assert_array_almost_equ...
def _print_preview(tab: apitypes.Tab) -> None: def print_callback(ok: bool) -> None: if (not ok): message.error('Printing failed!') tab.printing.check_preview_support() diag = QPrintPreviewDialog(tab) diag.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose) diag.setWindowFlags(((di...
class Info(OracleDatabase): def __init__(self, args): logging.debug('Info object created') OracleDatabase.__init__(self, args) self.version = '' self.os = '' def isVersion(self, version=None): if (version in self.version): return True else: ...
def process_camera_connector_chart(): connector_chart_dict = load_connector_chart() res = subprocess.run(['v4l2-ctl', '--list-devices'], stdout=subprocess.PIPE) output_string = res.stdout providers = [] topic_names = [] for (topic_name, usb_id) in connector_chart_dict.items(): dev_number...
def test_solver_returns_extras_if_requested_in_dependencies_and_not_in_root_package(solver: Solver, repo: Repository, package: ProjectPackage) -> None: package.add_dependency(Factory.create_dependency('A', '*')) package.add_dependency(Factory.create_dependency('B', '*')) package.add_dependency(Factory.creat...
def main(): default_cass = import_module('settings.default_cassandra') default_only_cass = import_module('settings.default_only_cassandra') secondary_cassandra = import_module('settings.secondary_cassandra') multi_cassandra = import_module('settings.multi_cassandra') metadata_disabled = import_modul...
class WhisperTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = MAX_MODEL_INPUT_SIZES model_input_names = ['input_ids', 'attention_mask'] def __init__(self, vocab_file, merges_file, normalizer_file=Non...
def monitor_kevent(ident: int, filter: int) -> ContextManager[_core.UnboundedQueue[select.kevent]]: locals()[LOCALS_KEY_KI_PROTECTION_ENABLED] = True try: return GLOBAL_RUN_CONTEXT.runner.io_manager.monitor_kevent(ident, filter) except AttributeError: raise RuntimeError('must be called from ...
def eval_train(model, device, train_loader): model.eval() train_loss = 0 correct = 0 with torch.no_grad(): for (data, target) in train_loader: (data, target) = (data.to(device), target.to(device)) output = model(data) train_loss += F.cross_entropy(output, targ...
_mode() def binary_recall_at_fixed_precision(input: torch.Tensor, target: torch.Tensor, *, min_precision: float) -> Tuple[(torch.Tensor, torch.Tensor)]: _binary_recall_at_fixed_precision_update_input_check(input, target, min_precision) return _binary_recall_at_fixed_precision_compute(input, target, min_precisio...
class IdleTask(Task): def __init__(self, i, p, w, s, r): Task.__init__(self, i, 0, None, s, r) def fn(self, pkt, r): i = r assert isinstance(i, IdleTaskRec) i.count -= 1 if (i.count == 0): return self.hold() elif ((i.control & 1) == 0): i.c...
def expectation_counts(counts: Dict[(str, int)]) -> Dict[(str, int)]: shots = np.sum(list(counts.values())) numq = len(list(counts.keys())[0]) subsets = [] for r in range(numq): subsets += list(combinations(range(numq), (r + 1))) exp_data = {'00': shots} for subset in subsets: ex...
def test_connection_request_key_header() -> None: with pytest.raises(RemoteProtocolError) as excinfo: _make_connection_request([(b'Host', b'localhost'), (b'Connection', b'Keep-Alive, Upgrade'), (b'Upgrade', b'websocket'), (b'Sec-WebSocket-Version', b'13')]) assert (str(excinfo.value) == "Missing header,...
def create_container(services=None, factory=Container): container = (factory(services) if services else factory()) if (not ('fs' in container)): import bonobo container.setdefault('fs', bonobo.open_fs()) if (not (' in container)): import requests container.setdefault(' reques...
.parametrize('linesep', ['\n', '\r\n']) def test_init_existing_pyproject_consistent_linesep(tester: CommandTester, source_dir: Path, init_basic_inputs: str, init_basic_toml: str, linesep: str) -> None: pyproject_file = (source_dir / 'pyproject.toml') existing_section = '\n[tool.black]\nline-length = 88\n'.repla...
('mmcv.__path__', [osp.join(osp.dirname(__file__), 'data/')]) def test_default_mmcv_home(): os.environ.pop(ENV_MMCV_HOME, None) os.environ.pop(ENV_XDG_CACHE_HOME, None) assert (_get_mmcv_home() == os.path.expanduser(os.path.join(DEFAULT_CACHE_DIR, 'mmcv'))) model_urls = get_external_models() assert ...
class TransformerLayer(nn.Module): def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm): super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention(dim, num_heads=num_heads, qkv_bias=q...
class TMVARegressor(TMVABase, Regressor): def __init__(self, method='kBDT', features=None, factory_options='', **method_parameters): TMVABase.__init__(self, factory_options=factory_options, method=method, **method_parameters) Regressor.__init__(self, features=features) def set_params(self, **par...
class PyrockoSourceDialog(SourceEditDialog): def __init__(self, delegate, ui_file, *args, **kwargs): SourceEditDialog.__init__(self, delegate, ui_file, *args, **kwargs) self.completer = QtWidgets.QCompleter() self.completer_model = QtGui.QFileSystemModel(self.completer) self.complete...
def extrinsic_events(network, previous_state, current_state, next_state, indices=None, major_complex=None): if major_complex: mc_nodes = major_complex.subsystem.node_indices elif indices: mc_nodes = indices else: major_complex = compute.network.major_complex(network, current_state) ...
def test_ddpg(): env = CartpoleEnv() policy = DeterministicMLPPolicy(env.spec) qf = ContinuousMLPQFunction(env.spec) es = OUStrategy(env.spec) algo = DDPG(env=env, policy=policy, qf=qf, es=es, n_epochs=1, epoch_length=100, batch_size=32, min_pool_size=50, replay_pool_size=1000, eval_samples=100) ...
class Marcus(BaseKinetics): def __init__(self, param, domain, reaction, options, phase='primary'): super().__init__(param, domain, reaction, options, phase) pybamm.citations.register('Sripad2020') def _get_kinetics(self, j0, ne, eta_r, T, u): RT = (self.param.R * T) Feta_RT = ((s...
.parametrize('fill_color', [(255, 255, 255, 255), (60, 70, 80, 100), (255, 255, 255, 255), (0, 255, 255, 255), (255, 0, 255, 255), (255, 255, 0, 255)]) def test_render_page_fill_color(fill_color, sample_page): kwargs = dict(fill_color=fill_color, scale=0.5) image = sample_page.render(**kwargs).to_pil() imag...
class LxDeviceFindByClassName(gdb.Function): def __init__(self): super(LxDeviceFindByClassName, self).__init__('lx_device_find_by_class_name') def invoke(self, cls, name): name = name.string() cls = get_class_by_name(cls.string()) for dev in class_for_each_device(cls): ...
class OPICHaircut(Haircut): def __init__(self, source, min_weight: float=0.001, tendency: float=0.7): super().__init__(source, min_weight) self.tendency = tendency def push(self, node, edges: list, **kwargs): (in_sum, out_sum) = (0, 0) (in_edges, out_edges) = (list(), list()) ...
class HTMLReporter(PythonTaReporter): name = 'HTMLReporter' _COLOURING = {'black': '<span class="black">', 'black-line': '<span class="black line-num">', 'bold': '<span>', 'code-heading': '<span>', 'style-heading': '<span>', 'code-name': '<span>', 'style-name': '<span>', 'highlight': '<span class="highlight-pyt...
class CmdPose(RPCommand): key = 'pose' def parse(self): args = self.args.strip() default = args.startswith('default') reset = args.startswith('reset') if default: args = re.sub('^default', '', args) if reset: args = re.sub('^reset', '', args) ...
def test_vertical_crs__from_methods(): assert_maker_inheritance_valid(VerticalCRS.from_epsg(5703), VerticalCRS) assert_maker_inheritance_valid(VerticalCRS.from_string('EPSG:5703'), VerticalCRS) with pytest.raises(CRSError, match='Invalid type'): VerticalCRS.from_proj4('+proj=latlon') assert_make...
def read_required(validator: Validator, required: List[str], instance: Any, schema: Mapping[(Hashable, Any)]) -> Iterator[ValidationError]: if (not validator.is_type(instance, 'object')): return for property in required: if (property not in instance): prop_schema = schema.get('proper...
class TypeHintingFactory(interfaces.ITypeHintingFactory): def make_param_provider(self): providers = [docstrings.ParamProvider(docstrings.DocstringParamParser(), self.make_resolver()), docstrings.ParamProvider(numpydocstrings.NumPyDocstringParamParser(), self.make_resolver())] return inheritance.Par...
class Solution(): def checkRecord(self, s: str) -> bool: A = 0 L = (- 1) if (s == ''): return True try: A = s.count('A') except: pass if (A > 1): return False try: L = s.find('LLL') except: ...