code
stringlengths
281
23.7M
class StatusBar(Gtk.HBox): def __init__(self, task_controller): super().__init__() self.__dirty = False self.set_spacing(12) self.task_controller = task_controller self.task_controller.parent = self self.default_label = Gtk.Label(selectable=True) self.default_...
def does_conv_have_relu_activation(input_op: Op) -> bool: if (input_op.type not in ['Conv2D', 'DepthwiseConv2dNative']): raise ValueError((('Op type: ' + input_op.type) + ' is not CONV2D!')) if ((len(input_op.output.consumers) == 1) and ((input_op.output.consumers[0].type == 'Relu') or (input_op.output....
def setUpModule(): global mol, mf mol = gto.Mole() mol.verbose = 7 mol.output = '/dev/null' mol.atom = [[8, (0.0, 0.0, 0.0)], [1, (0.0, (- 0.757), 0.587)], [1, (0.0, 0.757, 0.587)]] mol.spin = 2 mol.basis = '631g' mol.build() mf = scf.UHF(mol) mf.conv_tol_grad = 1e-08 mf.kern...
class TorsionProfileSmirnoff(TargetBase): target_name: Literal['TorsionProfile_SMIRNOFF'] = 'TorsionProfile_SMIRNOFF' description = 'Relaxed energy and RMSD fitting for torsion drives only.' energy_denom: PositiveFloat = Field(1.0, description='The energy denominator used by forcebalance to weight the energ...
def test_pattern_no_version_group(temp_dir): source = RegexSource(str(temp_dir), {'path': 'a/b', 'pattern': '.+'}) file_path = ((temp_dir / 'a') / 'b') file_path.ensure_parent_dir_exists() file_path.write_text('foo') with temp_dir.as_cwd(), pytest.raises(ValueError, match='no group named `version` w...
class TabBarStyle(QProxyStyle): ICON_PADDING = 4 def __init__(self, style=None): super().__init__(style) def _base_style(self) -> QStyle: style = self.baseStyle() assert (style is not None) return style def _draw_indicator(self, layouts, opt, p): color = opt.palet...
class BilinearUpsampling(Layer): def __init__(self, upsampling=(2, 2), output_size=None, data_format=None, **kwargs): super(BilinearUpsampling, self).__init__(**kwargs) self.data_format = K.normalize_data_format(data_format) self.input_spec = InputSpec(ndim=4) if output_size: ...
def test_pool_timeout_with_long_deadline_budget(): baseplate = _create_baseplate_object('5 milliseconds') baseplate.add_to_context('deadline_budget', 1000) context = baseplate.make_context_object() with baseplate.make_server_span(context, 'test'): with pytest.raises(ServerTimeout): g...
class BTOOLS_OT_add_fill(bpy.types.Operator): bl_idname = 'btools.add_fill' bl_label = 'Add Fill' bl_options = {'REGISTER', 'UNDO', 'PRESET'} props: bpy.props.PointerProperty(type=FillProperty) def poll(cls, context): return ((context.object is not None) and (context.mode == 'EDIT_MESH')) ...
def test_video_keywords(cipher_signature): expected = ['Rewind', 'Rewind 2019', 'youtube rewind 2019', '#YouTubeRewind', 'MrBeast', 'PewDiePie', 'James Charles', 'Shane Dawson', 'CaseyNeistat', 'RiceGum', 'Simone Giertz', 'JennaMarbles', 'Lilly Singh', 'emma chamberlain', 'The Try Guys', 'Fortnite', 'Minecraft', 'R...
def compute_parameters(node: FunctionNode, enclosing_class: Optional[TypedValue], ctx: Context, *, is_nested_in_class: bool=False, is_staticmethod: bool=False, is_classmethod: bool=False) -> Sequence[ParamInfo]: defaults = [_visit_default(node, ctx) for node in node.args.defaults] kw_defaults = [(None if (kw_de...
def convert_conv(vars, source_name, target_name, bias=True, start=0): weight = vars[(source_name + '/weight')].value().eval() dic = {'weight': weight.transpose((3, 2, 0, 1))} if bias: dic['bias'] = vars[(source_name + '/bias')].value().eval() dic_torch = {} dic_torch[(target_name + '.{}.weig...
class BasicConvolutionStack(ConvolutionStackInterface): def __init__(self, convolution_block: ConvolutionBlockInterface, layer_num_blocks: List[int]) -> None: self._convolution_block = convolution_block self._layer_num_blocks = layer_num_blocks def convolve(self, tensor: Tensor, num_filters: int...
class Mixable(EvscaperoomObject): mixer_flag = 'mixer' ingredient_recipe = ['ingredient1', 'ingredient2', 'ingredient3'] def at_object_creation(self): super().at_object_creation() self.set_flag(self.mixer_flag) self.db.ingredients = [] def check_mixture(self): ingredients...
class InceptionD(nn.Module): def __init__(self, in_channels, conv_block=None): super(InceptionD, self).__init__() if (conv_block is None): conv_block = BasicConv2d self.branch3x3_1 = conv_block(in_channels, 192, kernel_size=1) self.branch3x3_2 = conv_block(192, 320, kerne...
class GeneratorLatentFromNoise(): def __init__(self, name, fc_sizes=[128], latent_dim=128, activation_fn=tf.nn.relu, bn=True): self.name = name self.fc_sizes = fc_sizes.copy() self.latent_dim = latent_dim self.activation_fn = activation_fn self.bn = bn self.reuse = Fa...
class XLONExchangeCalendar(TradingCalendar): regular_early_close = time(12, 30) name = 'XLON' tz = timezone('Europe/London') open_times = ((None, time(8, 1)),) close_times = ((None, time(16, 30)),) def regular_holidays(self): return HolidayCalendar([LSENewYearsDay, GoodFriday, EasterMond...
def sq_relative(depth_pred, depth_gt): assert np.all((((np.isfinite(depth_pred) & np.isfinite(depth_gt)) & (depth_pred > 0)) & (depth_gt > 0))) diff = (depth_pred - depth_gt) num_pixels = float(diff.size) if (num_pixels == 0): return np.nan else: return (np.sum((np.square(diff) / dep...
def read_binary_image(file_path): img = cv2.imread(file_path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = (255 - gray) (ret, binary) = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY) (contours, hierarchy) = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) print(f'contour ...
class EscposIO(): def __init__(self, printer: Escpos, autocut: bool=True, autoclose: bool=True, **kwargs) -> None: self.printer = printer self.params = kwargs self.autocut = autocut self.autoclose = autoclose def set(self, **kwargs) -> None: self.params.update(kwargs) ...
class JobPreview(LoginRequiredMixin, JobDetail, UpdateView): template_name = 'jobs/job_detail.html' form_class = JobForm def get_success_url(self): return reverse('jobs:job_thanks') def post(self, request, *args, **kwargs): self.object = self.get_object() if (self.request.POST.ge...
def compute_align_loss(model, desc_enc, example): root_node = example.tree rel_cols = list(reversed([val for val in model.ast_wrapper.find_all_descendants_of_type(root_node, 'column')])) rel_tabs = list(reversed([val for val in model.ast_wrapper.find_all_descendants_of_type(root_node, 'table')])) rel_co...
def get_queries_from_smiles_and_query(smiles, query_smiles, fragment_filter, reporter): reporter.explain(f'Fragmenting {smiles} to find the query {query_smiles}') for frag_term in get_queries_from_smiles(smiles, fragment_filter, reporter): (frag_constant, frag_variables) = frag_term if (frag_var...
def test_newer_pairwise_group(groups_target): older = newer_pairwise_group([groups_target.older], [groups_target.target]) newer = newer_pairwise_group([groups_target.newer], [groups_target.target]) assert (older == ([], [])) assert (newer == ([groups_target.newer], [groups_target.target]))
def get_name_params_div(named_parameters1, named_parameters2=None, scalar=1.0): if (named_parameters2 is not None): common_names = list(set(named_parameters1.keys()).intersection(set(named_parameters2.keys()))) named_diff_parameters = {} for key in common_names: named_diff_parame...
def add_residual(x, brange, residual, residual_scale_factor, scaling_vector=None): if (scaling_vector is None): x_flat = x.flatten(1) residual = residual.flatten(1) x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor) else: ...
class _Selector(selectors._BaseSelectorImpl): def __init__(self, loop: SelectorEventLoop) -> None: super(_Selector, self).__init__() self._notified: Dict[(Any, Any)] = {} self._loop = loop self._event = None self._gevent_events: Dict[(Any, Any)] = {} if _GEVENT10: ...
class WindowCount(base._TextBox): defaults: list[tuple[(str, Any, str)]] = [('font', 'sans', 'Text font'), ('fontsize', None, 'Font pixel size. Calculated if None.'), ('fontshadow', None, 'font shadow color, default is None(no shadow)'), ('padding', None, 'Padding left and right. Calculated if None.'), ('foreground...
def test_run_with_optional_and_platform_restricted_dependencies(installer: Installer, locker: Locker, repo: Repository, package: ProjectPackage, mocker: MockerFixture) -> None: mocker.patch('sys.platform', 'darwin') package_a = get_package('A', '1.0') package_b = get_package('B', '1.1') package_c12 = ge...
class _ASPP(nn.Module): def __init__(self, in_channels=2048, out_channels=256): super().__init__() output_stride = cfg.MODEL.OUTPUT_STRIDE if (output_stride == 16): dilations = [6, 12, 18] elif (output_stride == 8): dilations = [12, 24, 36] elif (outpu...
class StateVariableType(GeneratedsSuper): __hash__ = GeneratedsSuper.__hash__ subclass = None superclass = None def __init__(self, sendEvents='yes', name=None, dataType=None, defaultValue=None, allowedValueList=None, allowedValueRange=None, gds_collector_=None, **kwargs_): self.gds_collector_ = ...
def process_batch_new(input_filename_list, input_label_list, dim_input, batch_sample_num, reshape_with_one=True): new_path_list = [] new_label_list = [] for k in range(batch_sample_num): class_idxs = range(0, FLAGS.way_num) random.shuffle(class_idxs) for class_idx in class_idxs: ...
def test_handle_inittarget_bad_expiration(): block_number = 1 pseudo_random_generator = random.Random() channels = make_channel_set([channel_properties]) expiration = ((channels[0].reveal_timeout + block_number) + 1) from_transfer = make_target_transfer(channels[0], expiration=expiration) channe...
def test_project_create_post_forbidden(db, client, settings): settings.PROJECT_CREATE_RESTRICTED = True client.login(username='user', password='user') url = reverse('project_create') data = {'title': 'A new project', 'description': 'Some description', 'catalog': catalog_id} response = client.post(ur...
class TwitterJSONIter(object): def __init__(self, handle, uri, arg_data, block, timeout, heartbeat_timeout): self.handle = handle self.uri = uri self.arg_data = arg_data self.timeout_token = Timeout self.timeout = None self.heartbeat_timeout = HEARTBEAT_TIMEOUT ...
class FastAttentionviaLowRankDecomposition(FastAttention): def __init__(self, matrix_creator, kernel_feature_creator, renormalize_attention, numerical_stabilizer, redraw_features, unidirectional, lax_scan_unroll=1): rng = random.PRNGKey(0) self.matrix_creator = matrix_creator self.projection...
def wrap_flask_restful_resource(fun: Callable, flask_restful_api: FlaskRestfulApi, injector: Injector) -> Callable: (fun) def wrapper(*args: Any, **kwargs: Any) -> Any: resp = fun(*args, **kwargs) if isinstance(resp, Response): return resp (data, code, headers) = flask_respon...
def is_natural_seq(evaluator, ab, cand_cdrs): with torch.no_grad(): batch = [] for cdr in cand_cdrs: ab = deepcopy(ab) ab['seq'] = ab['VH'].replace(ab['hcdr3'], cdr) batch.append(ab) (hX, hS, hL, hmask) = completize(batch) cand_ppl1 = evaluator[0]....
def test_pycode_replace_objects(): pycode = "context['alist'] = [0, 1, 2]\ncontext['adict'] = {'a': 'b', 'c': 'd'}\ncontext['anint'] = 456\ncontext['mutate_me'].append(12)\ncontext['astring'] = 'updated'\n" context = Context({'alist': [0, 1], 'adict': {'a': 'b'}, 'anint': 123, 'mutate_me': [10, 11], 'astring': ...
def update_output_for_test(type_checker: TypeChecker, results_dir: Path, test_case: Path, output: str): test_name = test_case.stem output = f''' {output}''' results_file = (results_dir / f'{test_name}.toml') results_file.parent.mkdir(parents=True, exist_ok=True) try: with open(results_file, ...
def test_PVSystem_pvwatts_dc_kwargs(pvwatts_system_kwargs, mocker): mocker.spy(pvsystem, 'pvwatts_dc') irrad = 900 temp_cell = 30 expected = 90 out = pvwatts_system_kwargs.pvwatts_dc(irrad, temp_cell) pvsystem.pvwatts_dc.assert_called_once_with(irrad, temp_cell, **pvwatts_system_kwargs.arrays[0]...
('/v1/organization/<orgname>/collaborators') _param('orgname', 'The name of the organization') class OrganizationCollaboratorList(ApiResource): _scope(scopes.ORG_ADMIN) ('getOrganizationCollaborators') def get(self, orgname): permission = AdministerOrganizationPermission(orgname) if (not per...
def find_executable(executable, path=None): (_, ext) = os.path.splitext(executable) if ((sys.platform == 'win32') and (ext != '.exe')): executable = (executable + '.exe') if os.path.isfile(executable): return executable if (path is None): path = os.environ.get('PATH', None) ...
(eq=False, hash=False, slots=True) class Runner(): clock: Clock = attr.ib() instruments: Instruments = attr.ib() io_manager: TheIOManager = attr.ib() ki_manager: KIManager = attr.ib() strict_exception_groups: bool = attr.ib() _locals: dict[(_core.RunVar[Any], Any)] = attr.ib(factory=dict) ru...
class AmplitudeEstimationResult(AmplitudeEstimationAlgorithmResult): def ml_value(self) -> float: return self.get('ml_value') _value.setter def ml_value(self, value: float) -> None: self.data['ml_value'] = value def mapped_a_samples(self) -> List[float]: return self.get('mapped_a...
class Scoreboard(uvm_component): def build_phase(self): self.cmd_fifo = uvm_tlm_analysis_fifo('cmd_fifo', self) self.result_fifo = uvm_tlm_analysis_fifo('result_fifo', self) self.cmd_get_port = uvm_get_port('cmd_get_port', self) self.result_get_port = uvm_get_port('result_get_port', ...
class TesttestLine(): def test___init__1(self): for (m, b) in [(4, 0.0), ((- 140), 5), (0, 0)]: _ = Line(m, b) def test_y1(self): l_ = Line(0, 0) assert (l_.y(0) == 0) assert (l_.y((- 1e309)) == 0) assert (l_.y(1e309) == 0) l_ = Line(1, 1) asse...
.skipif('sys.platform == "win32"', reason="SIGTERM isn't really supported on Windows") .xfail('sys.platform == "darwin"', reason='Something weird going on Macs...') .xfail('platform.python_implementation() == "PyPy"', reason='Interpreter seems buggy') .parametrize('setup', [('signal.signal(signal.SIGTERM, signal.SIG_DF...
.parametrize('bad_level', [None, (- 2), 3]) def test_set_propagate_cast_with_bad_level(bad_level): (D_in, H, D_out) = (784, 500, 10) model = NeuralNetSinglePositionalArgument(D_in, H, D_out) model = ORTModule(model) strategy = PropagateCastOpsStrategy.INSERT_AND_REDUCE with pytest.raises(TypeError) ...
def name_replacer(match: re.Match[str]): (prefix, resource) = match.group('prefix', 'resource') override_prefix = prefix.replace('file_filter', 'trans.zh_CN') pattern = resource.replace('trans/<lang>/', '').replace('glossary_', 'glossary').replace('--', '/').replace('_', '?') matches = list(glob.glob(pa...
.unit() .skipif((sys.platform != 'win32'), reason='Only works on Windows.') .parametrize(('path', 'existing_paths', 'expected'), [pytest.param('text.txt', [], 'text.txt', id='non-existing path stays the same'), pytest.param('text.txt', ['text.txt'], 'text.txt', id='existing path is same'), pytest.param('Text.txt', ['te...
class FeedForwardModule(nn.Module): def __init__(self, dim, hidden_dim_multiplier, dropout, input_dim_multiplier=1, **kwargs): super().__init__() input_dim = int((dim * input_dim_multiplier)) hidden_dim = int((dim * hidden_dim_multiplier)) self.linear_1 = nn.Linear(in_features=input_...
class GLGradientLegendItem(GLGraphicsItem): def __init__(self, parentItem=None, **kwds): super().__init__(parentItem=parentItem) glopts = kwds.pop('glOptions', 'additive') self.setGLOptions(glopts) self.pos = (10, 10) self.size = (10, 100) self.fontColor = QtGui.QColo...
class OpenQASampler(Sampler): def __init__(self, data_source, batch_size): self.batch_size = batch_size sample_indice = [] for qa_idx in range(len(data_source.qids)): batch_data = [] batch_data.append(random.choice(data_source.grouped_idx_has_answer[qa_idx])) ...
def identity_with_metadata_simple(use): ints = use.init_artifact('ints', ints1_factory) md = use.init_metadata('md', md1_factory) use.action(use.UsageAction(plugin_id='dummy_plugin', action_id='identity_with_metadata'), use.UsageInputs(ints=ints, metadata=md), use.UsageOutputNames(out='out'))
def test_get_identifications_by_id(requests_mock): mock_response = load_sample_data('get_identifications.json') mock_response['results'] = [mock_response['results'][0]] requests_mock.get(f'{API_V1}/identifications/', json=mock_response, status_code=200) response = get_identifications_by_id() assert ...
def test_postgenerationmethodcall_getfixturevalue(request, factoryboy_request): secret = request.getfixturevalue('foo__secret') number = request.getfixturevalue('foo__number') assert (not factoryboy_request.deferred) assert (secret == 'super secret') assert (number is NotProvided)
class Encoder(nn.Module): def __init__(self, hidden_channels, sample_size, sample_duration): super(Encoder, self).__init__() self.convlstm = ConvLSTM(input_channels=3, hidden_channels=hidden_channels, kernel_size=3, step=sample_duration, effective_step=[(sample_duration - 1)]) self.conv2 = n...
def test_solver_can_resolve_directory_dependencies_with_extras(solver: Solver, repo: Repository, package: ProjectPackage, fixture_dir: FixtureDirGetter) -> None: pendulum = get_package('pendulum', '2.0.3') cleo = get_package('cleo', '1.0.0') repo.add_package(pendulum) repo.add_package(cleo) path = (...
def get_missing(po_dir: Path) -> Iterable[str]: src_root = _src_root(po_dir) potfiles_path = (po_dir / 'POTFILES.in') skip_path = (po_dir / 'POTFILES.skip') pot_files = {p.relative_to(src_root) for p in _read_potfiles(src_root, potfiles_path)} skip_files = {p.relative_to(src_root) for p in _read_pot...
class QuestionAdminForm(ElementAdminForm): widget_type = forms.ChoiceField(choices=get_widget_type_choices()) class Meta(): model = Question fields = '__all__' def clean(self): QuestionUniqueURIValidator(self.instance)(self.cleaned_data) QuestionLockedValidator(self.instance)...
class ExtractFactory(object): current_extracts = {'default': Extract, 'regex': RegExtract, 'cot-commonsense_qa': CoTCommonsenseQAExtract} def get_extract(extract: str) -> Type[Extract]: if (extract in ExtractFactory.current_extracts): return ExtractFactory.current_extracts[extract] e...
def bench_dumping(lazy_compilation: bool): if lazy_compilation: data = create_response(GetRepoIssuesResponseLC, IssueLC, ReactionsLC, PullRequestLC, LabelLC, SimpleUserLC) data.to_dict() else: data = create_response(GetRepoIssuesResponse, Issue, Reactions, PullRequest, Label, SimpleUser)...
class TimerWidget(Image): icon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACkAAAAvCAYAAAB+OePrAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAABswAAAbMBHmbrhwAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAkTSURBVFiFvZltcFTlFcd/594lb0JChCoUqsEiSLGWQkbbsdo4yMQZsluazlptB0sh3KShjtLOVOuo3daO1nbUDwqTuxuZiKPVItbsJsE3OvGtdipY...
class GetScreenInfo(rq.ReplyRequest): _request = rq.Struct(rq.Card8('opcode'), rq.Opcode(5), rq.RequestLength(), rq.Window('window')) _reply = rq.Struct(rq.ReplyCode(), rq.Card8('set_of_rotations'), rq.Card16('sequence_number'), rq.ReplyLength(), rq.Window('root'), rq.Card32('timestamp'), rq.Card32('config_time...
class ShelfBinPacker(object): def __init__(self, dims: mn.Range2D): self.dims = dims self.shelves: List[Shelf] = [] self.matches: Dict[(int, Match)] = {} def assert_consistency(self): for (prev, next) in zip(self.shelves[:(- 1)], self.shelves[1:]): if ((prev.dims.top ...
class PlayControls(Gtk.VBox): def __init__(self, player, library): super().__init__(spacing=3) upper = Gtk.Table(n_rows=1, n_columns=3, homogeneous=True) upper.set_row_spacings(3) upper.set_col_spacings(3) prev = Gtk.Button(relief=Gtk.ReliefStyle.NONE) prev.add(Symbol...
def SaveScene(scene, project, path): location = (project.path / path) data = [ObjectInfo('Scene', project.GetUuid(scene), {'name': scene.name, 'mainCamera': ObjectInfo.SkipConv(project.GetUuid(scene.mainCamera))})] SaveGameObjects(scene.gameObjects, data, project) location.parent.mkdir(parents=True, exi...
class GlobalScope(Scope): def __init__(self, pycore, module): super().__init__(pycore, module, None) self.names = module._get_concluded_data() def get_start(self): return 1 def get_kind(self): return 'Module' def get_name(self, name): try: return self....
def main(): parser = argparse.ArgumentParser(description='Train a model on the Hotpot pairwise relevance dataset') parser.add_argument('name', help='Where to store the model') parser.add_argument('-c', '--continue_model', action='store_true', help='Whether to start a new run or continue an existing one') ...
class GenericLastTransitionLogTestCase(test.TestCase): def setUp(self): self.obj = models.GenericWorkflowEnabled.objects.create() def test_transitions(self): self.assertEqual(0, models.GenericWorkflowLastTransitionLog.objects.count()) self.obj.ab() self.assertEqual(1, models.Gene...
class InfluxClient(object): def __init__(self, data_manger, config): self.data_manager = data_manger self.config = config self.logger = getLogger() self.influx = InfluxDBClient(host=self.config.influx_url, port=self.config.influx_port, username=self.config.influx_username, password=s...
class WebhookRequestBodyValidator(BaseWebhookRequestValidator): def iter_errors(self, request: WebhookRequest) -> Iterator[Exception]: try: (_, operation, _, _, _) = self._find_path(request) except PathError as exc: (yield exc) return (yield from self._ite...
class AnnotatedObjectsCoco(AnnotatedObjectsDataset): def __init__(self, use_things: bool=True, use_stuff: bool=True, **kwargs): super().__init__(**kwargs) self.use_things = use_things self.use_stuff = use_stuff with open(self.paths['instances_annotations']) as f: inst_dat...
class FlyController(Controller): _default_controls = {'mouse1': ('rotate', 'drag', (0.005, 0.005)), 'q': ('roll', 'repeat', (- 2)), 'e': ('roll', 'repeat', (+ 2)), 'w': ('move', 'repeat', (0, 0, (- 1))), 's': ('move', 'repeat', (0, 0, (+ 1))), 'a': ('move', 'repeat', ((- 1), 0, 0)), 'd': ('move', 'repeat', ((+ 1), ...
class Transformer2DModel(ModelMixin, ConfigMixin): _to_config def __init__(self, num_attention_heads: int=16, attention_head_dim: int=88, in_channels: Optional[int]=None, num_layers: int=1, dropout: float=0.0, norm_num_groups: int=32, cross_attention_dim: Optional[int]=None, attention_bias: bool=False, sample_s...
_on_failure .parametrize('number_of_nodes', [1]) .parametrize('channels_per_node', [0]) .parametrize('number_of_tokens', [0]) .parametrize('environment_type', [Environment.DEVELOPMENT]) def test_deposit_amount_must_be_smaller_than_the_token_network_limit(raiden_network: List[RaidenService], contract_manager: ContractMa...
class SkipDownBlock2D(nn.Module): def __init__(self, in_channels: int, out_channels: int, temb_channels: int, dropout: float=0.0, num_layers: int=1, resnet_eps: float=1e-06, resnet_time_scale_shift: str='default', resnet_act_fn: str='swish', resnet_pre_norm: bool=True, output_scale_factor=np.sqrt(2.0), add_downsamp...
def convert_cityscapes_instance_only(data_dir, out_dir): sets = ['gtFine_val', 'gtFine_train', 'gtFine_test'] ann_dirs = ['gtFine_trainvaltest/gtFine/val', 'gtFine_trainvaltest/gtFine/train', 'gtFine_trainvaltest/gtFine/test'] json_name = 'instancesonly_filtered_%s.json' ends_in = '%s_polygons.json' ...
def test(capfd, tmp_path): project_dir = (tmp_path / 'project') subdir_package_project.generate(project_dir) package_dir = Path('src', 'spam') actual_wheels = utils.cibuildwheel_run(project_dir, package_dir=package_dir, add_env={'CIBW_BEFORE_BUILD': 'python {project}/bin/before_build.py', 'CIBW_TEST_COM...
class OldUserData(AbstractData): __slots__ = ['name', 'email', 'role', 'permission', 'template_name'] def __init__(self, name=None, email=None, role=None, permission=None, template_name=None): self.name = name self.email = email self.role = role self.permission = permission ...
class SaveMixin(_RestObjectBase): _id_attr: Optional[str] _attrs: Dict[(str, Any)] _module: ModuleType _parent_attrs: Dict[(str, Any)] _updated_attrs: Dict[(str, Any)] manager: base.RESTManager def _get_updated_data(self) -> Dict[(str, Any)]: updated_data = {} for attr in sel...
def test_import(module, allow_conflict_names, fun, error): from datar import options options(allow_conflict_names=allow_conflict_names) if (not error): return _import(module, fun) try: _import(module, fun) except Exception as e: raised = type(e).__name__ assert (raise...
class LazyCommandInterface(CommandInterface): def execute(self, call: CommandGraphCall, args: tuple, kwargs: dict) -> LazyCall: return LazyCall(call, args, kwargs) def has_command(self, node: CommandGraphNode, command: str) -> bool: return True def has_item(self, node: CommandGraphNode, obje...
class Graphsn_GCN(Module): def __init__(self, in_features, out_features, bias=True): super(Graphsn_GCN, self).__init__() self.in_features = in_features self.out_features = out_features self.weight = Parameter(torch.FloatTensor(in_features, out_features)) self.eps = nn.Paramet...
def main(client, config): (ws_df, ss_df, date_df, customer_df) = benchmark(read_tables, config=config, compute_result=config['get_read_time']) filtered_date_df = date_df.query(f'd_year >= {q06_YEAR} and d_year <= {(q06_YEAR + 1)}', meta=date_df._meta).reset_index(drop=True) web_sales_df = ws_df.merge(filter...
class NERTrainer(): def __init__(self, config: TrainerConfig, datasets: Tuple[(list, list, list)]): super(NERTrainer, self).__init__() writer_folder = os.path.join(config.output_folder, 'summary') if (not os.path.isdir(writer_folder)): os.makedirs(writer_folder) self._con...
def attention_model(images, texts, model_name, is_training=False, weight_decay=4e-05, scope='attention'): with tf.variable_scope(scope): arg_scope = nets_factory.arg_scopes_map[model_name](weight_decay=weight_decay) with slim.arg_scope(arg_scope): with slim.arg_scope([slim.batch_norm, sl...
class IssueResource(models.Model): issue = models.ForeignKey('Issue', on_delete=models.CASCADE, related_name='resources', verbose_name=_('Issue'), help_text=_('The issue for this issue resource.')) integration = models.ForeignKey('Integration', on_delete=models.CASCADE, related_name='resources', verbose_name=_(...
((not has_working_ipv6()), 'Requires IPv6') (os.environ.get('SKIP_IPV6'), 'IPv6 tests disabled') def test_filter_address_by_type_from_service_info(): desc = {'path': '/~paulsm/'} type_ = '_homeassistant._tcp.local.' name = 'MyTestHome' registration_name = f'{name}.{type_}' ipv4 = socket.inet_aton('1...
def load_centralized_mnist(dataset, data_dir, batch_size, max_train_len=None, max_test_len=None, args=None): MNIST_MEAN = (0.1307,) MNIST_STD = (0.3081,) image_size = 28 train_transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean=MNIST_MEAN, std=MNIST_STD)]) test_transform...
def process_dis_batch_2_new(input_filename_list, dim_input, num, reshape_with_one=False): img_list = [] random.seed(6) random.shuffle(input_filename_list) for filepath in input_filename_list: filepath2 = (FLAGS.data_path + filepath) this_img = scm.imread(filepath2) this_img = np....
def anonymize_relaxed(partition): if (sum(partition.allow) == 0): RESULT.append(partition) return dim = choose_dimension(partition) if (dim == (- 1)): print('Error: dim=-1') pdb.set_trace() (split_val, next_val, low, high) = find_median(partition, dim) if (low is not ...
class ContextRes(): def __init__(self, gf_dim=64, df_dim=64, gfc_dim=1024, dfc_dim=1024, c_dim=3): self.gf_dim = gf_dim self.df_dim = df_dim self.c_dim = c_dim self.gfc_dim = gfc_dim self.dfc_dim = dfc_dim def build(self, image): imgshape = image.get_shape().as_li...
def test_detect_clearsky_time_interval(detect_clearsky_data): (expected, cs) = detect_clearsky_data u = np.arange(0, len(cs), 2) cs2 = cs.iloc[u] expected2 = expected.iloc[u] clear_samples = clearsky.detect_clearsky(expected2['GHI'], cs2['ghi'], window_length=6) assert_series_equal(expected2['Cl...
def build_base_model(model_opt, fields, gpu, checkpoint=None, gpu_id=None): try: model_opt.attention_dropout except AttributeError: model_opt.attention_dropout = model_opt.dropout if ((model_opt.model_type == 'text') or (model_opt.model_type == 'vec')): src_field = fields['src'] ...
def set_arg(config_dict, params, arg_name, arg_type): for (_i, _v) in enumerate(params): if (_v.split('=')[0] == arg_name): arg_name = _v.split('=')[0].replace('--', '') arg_value = _v.split('=')[1] config_dict[arg_name] = arg_type(arg_value) del params[_i] ...
def make_unsigned_request(req: 'OnchainInvoice'): addr = req.get_address() time = req.time exp = req.exp if (time and (type(time) != int)): time = 0 if (exp and (type(exp) != int)): exp = 0 amount = req.amount_sat if (amount is None): amount = 0 memo = req.message...
class DescribeTable(): def it_can_add_a_row(self, add_row_fixture): (table, expected_xml) = add_row_fixture row = table.add_row() assert (table._tbl.xml == expected_xml) assert isinstance(row, _Row) assert (row._tr is table._tbl.tr_lst[(- 1)]) assert (row._parent is t...
class TestSecurityOverride(): host_url = ' api_key = '12345' def api_key_encoded(self): api_key_bytes = self.api_key.encode('utf8') api_key_bytes_enc = b64encode(api_key_bytes) return str(api_key_bytes_enc, 'utf8') def test_default(self, request_unmarshaller): args = {'ap...