code
stringlengths
281
23.7M
def datetime_to_djd(time): if (time.tzinfo is None): time_utc = pytz.utc.localize(time) else: time_utc = time.astimezone(pytz.utc) djd_start = pytz.utc.localize(dt.datetime(1899, 12, 31, 12)) djd = (((time_utc - djd_start).total_seconds() * 1.0) / ((60 * 60) * 24)) return djd
class ScriptMakerCustom(ScriptMaker): def __init__(self, target_dir, version_info, executable, name) -> None: super().__init__(None, str(target_dir)) self.clobber = True self.set_mode = True self.executable = enquote_executable(str(executable)) self.version_info = (version_in...
def read_file_list(): basedir = (radare2_includedir + '/') return [(basedir + 'r_core.h'), (basedir + 'r_asm.h'), (basedir + 'r_anal.h'), (basedir + 'r_bin.h'), (basedir + 'r_debug.h'), (basedir + 'r_io.h'), (basedir + 'r_config.h'), (basedir + 'r_flag.h'), (basedir + 'r_sign.h'), (basedir + 'r_hash.h'), (based...
def adjust_rel_elec_density(dicom_dataset, adjustment_map, ignore_missing_structure=False): new_dicom_dataset = deepcopy(dicom_dataset) ROI_name_to_number_map = {structure_set.ROIName: structure_set.ROINumber for structure_set in new_dicom_dataset.StructureSetROISequence} ROI_number_to_observation_map = {ob...
class GraphRewriter(Rewriter): def apply(self, fgraph): raise NotImplementedError() def rewrite(self, fgraph, *args, **kwargs): self.add_requirements(fgraph) return self.apply(fgraph, *args, **kwargs) def __call__(self, fgraph): return self.rewrite(fgraph) def add_require...
class TableTruncate(ABC): def __init__(self, tokenizer: BasicTokenizer=None, max_input_length: int=1024): if (tokenizer is None): self.tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path='facebook/bart-large') else: self.tokenizer = tokenizer self....
def keras_model(): model = Sequential([Conv2D(8, (2, 2), input_shape=(16, 16, 3)), BatchNormalization(momentum=0.3, epsilon=0.65), AvgPool2D(), MaxPool2D(), BatchNormalization(momentum=0.4, epsilon=0.25), Conv2D(4, (2, 2), activation=tf.nn.tanh, kernel_regularizer=tf.keras.regularizers.l2(0.5)), Flatten(), Dense(2,...
class COCOFeaturesDataset(BaseFeaturesDataset): def __init__(self, *args, **kwargs): super(COCOFeaturesDataset, self).__init__() self.feature_readers = [] self.feature_dict = {} self.fast_read = kwargs['fast_read'] self.writer = registry.get('writer') for image_featur...
def get_preprocessor(model_name: str) -> Optional[Union[('AutoTokenizer', 'AutoFeatureExtractor', 'AutoProcessor')]]: from .. import AutoFeatureExtractor, AutoProcessor, AutoTokenizer try: return AutoProcessor.from_pretrained(model_name) except (ValueError, OSError, KeyError): (tokenizer, fe...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, norm_layer=nn.BatchNorm2d): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False) self.bn1 = norm_layer(planes) self.conv2 = nn.Conv2d(p...
('lr_scheduler', 'warmup_polynomial') class WarmupPolynomialLRScheduler(): param_groups = attr.ib() num_warmup_steps = attr.ib() start_lr = attr.ib() end_lr = attr.ib() decay_steps = attr.ib() power = attr.ib() def update_lr(self, current_step): if (current_step < self.num_warmup_ste...
def test_list_from_file(): with tempfile.TemporaryDirectory() as tmpdirname: for (i, lines) in enumerate(lists): filename = f'{tmpdirname}/{i}.txt' with open(filename, 'w', encoding='utf-8') as f: f.writelines((f'''{line} ''' for line in lines)) lines2 = l...
class LFPluginCollWrapper(): def __init__(self, lfplugin: 'LFPlugin') -> None: self.lfplugin = lfplugin self._collected_at_least_one_failure = False (wrapper=True) def pytest_make_collect_report(self, collector: nodes.Collector) -> Generator[(None, CollectReport, CollectReport)]: res...
class PositionConfig(Config): auto_fullscreen = True groups = [config.Group('a'), config.Group('b')] layouts = [layout.MonadTall(), layout.TreeTab()] floating_layout = resources.default_config.floating_layout keys = [] mouse = [] screens = [] follow_mouse_focus = False
def repo_with_no_tags_emoji_commits(git_repo_factory, file_in_repo): git_repo = git_repo_factory() add_text_to_file(git_repo, file_in_repo) git_repo.git.commit(m='Initial commit') add_text_to_file(git_repo, file_in_repo) git_repo.git.commit(m=':bug: add some more text') add_text_to_file(git_repo...
class TestOptional(): def test_success_with_type(self): c = optional(int) assert (c('42') == 42) def test_success_with_none(self): c = optional(int) assert (c(None) is None) def test_fail(self): c = optional(int) with pytest.raises(ValueError): c('...
class CmdLineApp(cmd.Cmd): MUMBLES = ['like', '...', 'um', 'er', 'hmmm', 'ahh'] MUMBLE_FIRST = ['so', 'like', 'well'] MUMBLE_LAST = ['right?'] def do_exit(self, line): return True do_EOF = do_exit do_quit = do_exit def do_speak(self, line): print(line, file=self.stdout) d...
def flat_xml_to_elements(root): elements = {} ns_map = get_ns_map(root) uri_attrib = get_ns_tag('dc:uri', ns_map) for node in root: uri = get_uri(node, ns_map) element = {'uri': get_uri(node, ns_map), 'model': models[node.tag]} for sub_node in node: tag = strip_ns(sub...
class KnownValues(unittest.TestCase): def test_tda(self): td = tdscf.TDA(mf).run(nstates=nstates) tdg = td.nuc_grad_method() g1 = tdg.kernel(state=3) self.assertAlmostEqual(g1[(0, 2)], (- 0.), 5) td_solver = td.as_scanner() e1 = td_solver(pmol.set_geom_('H 0 0 1.805; ...
class Effect6599(BaseEffect): type = 'passive' def handler(fit, src, context, projectionRange, **kwargs): fit.ship.boostItemAttr('armorKineticDamageResonance', src.getModifiedItemAttr('shipBonusCarrierA1'), skill='Amarr Carrier', **kwargs) fit.ship.boostItemAttr('armorEmDamageResonance', src.get...
def create_h5_sdf_pt(h5_file, sdf_file, norm_obj_file, centroid, m, sdf_res, num_sample, bandwidth, iso_val, max_verts, normalize, reduce=8): sdf_dict = get_sdf(sdf_file, sdf_res) ori_verts = np.asarray([0.0, 0.0, 0.0], dtype=np.float32).reshape((1, 3)) (samplesdf, is_insideout) = sample_sdf(num_sample, ban...
class EOH(QuantumAlgorithm): def __init__(self, operator: LegacyBaseOperator, initial_state: Union[(InitialState, QuantumCircuit)], evo_operator: LegacyBaseOperator, evo_time: float=1, num_time_slices: int=1, expansion_mode: str='trotter', expansion_order: int=1, quantum_instance: Optional[Union[(QuantumInstance, B...
class HSAFFileHandler(BaseFileHandler): def __init__(self, filename, filename_info, filetype_info): super(HSAFFileHandler, self).__init__(filename, filename_info, filetype_info) self._msg_datasets = {} self._start_time = None self._end_time = None try: with pygrib...
class TestVariableModule(TestCase): def test_is_list_of_tuples(self): a_list = [(1, 2), (3, 4)] self.assertEqual(variable.is_list_of_tuples(a_list), (True, a_list)) a_list = [1, 2, 3, 4] self.assertEqual(variable.is_list_of_tuples(a_list), (False, None)) def test_list_test(self):...
def call_optional(obj: object, name: str, nodeid: str) -> bool: method = getattr(obj, name, None) if (method is None): return False is_fixture = (getfixturemarker(method) is not None) if is_fixture: return False if (not callable(method)): return False method_name = getatt...
def init_pretrained_weights(model, model_url): if (model_url is None): import warnings warnings.warn('ImageNet pretrained weights are unavailable for this model') return pretrain_dict = model_zoo.load_url(model_url) model_dict = model.state_dict() pretrain_dict = {k: v for (k, v)...
def enum_assemble(node, neighbors, prev_nodes=[], prev_amap=[]): all_attach_confs = [] singletons = [nei_node.nid for nei_node in (neighbors + prev_nodes) if (nei_node.mol.GetNumAtoms() == 1)] def search(cur_amap, depth): if (len(all_attach_confs) > MAX_NCAND): return if (depth =...
class RelatednessPytorch(object): def __init__(self, train, valid, test, devscores, config): np.random.seed(config['seed']) torch.manual_seed(config['seed']) assert torch.cuda.is_available(), 'torch.cuda required for Relatedness' torch.cuda.manual_seed(config['seed']) self.tr...
def get_inverse_hvp_lissa(v, model, device, param_influence, train_loader, damping, num_samples, recursion_depth, scale=10000.0): ihvp = None for i in range(num_samples): cur_estimate = v lissa_data_iterator = iter(train_loader) for j in range(recursion_depth): try: ...
def _intensity_validator(value, values): if (not isinstance(value, tuple)): raise ValueError('Input value {} of trigger_select should be a tuple'.format(value)) if (len(value) != 2): raise ValueError('Number of parameters {} different from 2'.format(len(value))) for i in range(2): st...
def table_to_file(table: pa.Table, base_path: str, file_system: AbstractFileSystem, block_path_provider: BlockWritePathProvider, content_type: str=ContentType.PARQUET.value, **kwargs) -> None: writer = CONTENT_TYPE_TO_PA_WRITE_FUNC.get(content_type) if (not writer): raise NotImplementedError(f"Pyarrow w...
class Rumor_Data(Dataset): def __init__(self, dataset): self.text = torch.from_numpy(np.array(dataset['post_text'])) self.image = list(dataset['image']) self.mask = torch.from_numpy(np.array(dataset['mask'])) self.label = torch.from_numpy(np.array(dataset['label'])) self.even...
class SNDCGAN_Discrminator(object): def __init__(self, batch_size=64, hidden_activation=lrelu, output_dim=1, scope='critic', **kwargs): self.batch_size = batch_size self.hidden_activation = hidden_activation self.output_dim = output_dim self.scope = scope def __call__(self, x, up...
def plot_time_cost(title, yrange, fed_async, fed_avg, fed_sync, fed_localA, local_train, fed_asofed, fed_bdfl, save_path=None, plot_size='L'): font_settings = get_font_settings(plot_size) x = range(1, (len(fed_async) + 1)) (fig, axes) = plt.subplots() axes.plot(x, fed_async, label='DBAFL', linewidth=3, ...
def channel_shuffle(x, groups): (batchsize, num_channels, height, width) = x.data.size() channels_per_group = (num_channels // groups) x = x.view(batchsize, groups, channels_per_group, height, width) x = torch.transpose(x, 1, 2).contiguous() x = x.view(batchsize, (- 1), height, width) return x
def pick_slices(img, view_set, num_slices): slices = list() for view in view_set: dim_size = img.shape[view] non_empty_slices = np.array([sl for sl in range(dim_size) if (np.count_nonzero(get_axis(img, view, sl)) > 0)]) num_non_empty = len(non_empty_slices) skip_count = max(0, np...
def main(): ops.survey.print_header('Uptime') uptime = ops.system.get_uptime() if (uptime is None): dsz.Sleep(5000) uptime = ops.system.get_uptime() if (uptime is None): ops.error('Could not properly find process list to calculate uptime, you might have to do the math on your own...
def catalyze_one_step_reversible(enzyme, substrate, product, klist): if isinstance(enzyme, Monomer): enzyme = enzyme() if isinstance(substrate, Monomer): substrate = substrate() if isinstance(product, Monomer): product = product() components = catalyze_one_step(enzyme, substrate,...
def main(argv): mutate_sys_path() assert ('doctest' not in sys.modules) import testprogram this_dir = os.path.dirname(__file__) prog = testprogram.TestProgram(argv=argv, default_discovery_args=(this_dir, '*.py', None), module=None) result = prog.runTests() success = result.wasSuccessful() ...
_common_args def get_observation_taxon_summary(observation_id: int, **params) -> JsonResponse: results = get(f'{API_V1}/observations/{observation_id}/taxon_summary', **params).json() results['conservation_status'] = convert_generic_timestamps(results['conservation_status']) results['listed_taxon'] = convert...
def test_infer_norm_abbr(): with pytest.raises(TypeError): infer_norm_abbr(0) class MyNorm(): _abbr_ = 'mn' assert (infer_norm_abbr(MyNorm) == 'mn') class FancyBatchNorm(): pass assert (infer_norm_abbr(FancyBatchNorm) == 'bn') class FancyInstanceNorm(): pass a...
class SortFilterProxyModel(QSortFilterProxyModel): def filterAcceptsRow(self, sourceRow, sourceParent): if (self.filterKeyColumn() == DATE): index = self.sourceModel().index(sourceRow, DATE, sourceParent) data = self.sourceModel().data(index) return (self.filterRegExp().i...
class OperatorBase(ABC): INDENTATION = ' ' ENABLE_DEPRECATION = True def __init__(self) -> None: super().__init__() if OperatorBase.ENABLE_DEPRECATION: warn_package('aqua.operators', 'qiskit.opflow', 'qiskit-terra') def num_qubits(self) -> int: raise NotImplementedEr...
class ValidatingRequestsSession(requests.Session): def __init__(self, *args, checksum_algorithm=hashlib.sha256, **kwargs): super().__init__(*args, **kwargs) self._algorithm = checksum_algorithm def get(self, url, checksum, **kwargs): kwargs.setdefault('allow_redirects', True) ret...
def plot_unions_HTS(results, size, metric: str='greedy'): (fig, axs) = plt.subplots(1, 3, sharey=True, figsize=(((4 / 1.5) * 3), 4)) fmt = 'o-' ms = 5 for (i, (split, ax)) in enumerate(zip(SPLITS, axs)): xs = [int(((size * split) * i)) for i in range(1, 7)] for model in MODELS: ...
class ConversationsGeneratorConfig(): openai_api_key: str agent1: str agent2: str initial_utterances: List[str] = field(default_factory=(lambda : ['Hello.'])) num_samples: int = 1 interruption: str = 'length' end_phrase: str = 'Goodbye!' end_agent: str = 'both' lengths: List[int] = f...
class ConditionReturn(): condition: Condition left_varmap: Optional[VarMap] = None right_varmap: Optional[VarMap] = None def reverse(self) -> 'ConditionReturn': return ConditionReturn(left_varmap=self.right_varmap, right_varmap=self.left_varmap, condition=NotCondition(self.condition))
def test_exclude_from_history(base_app): run_cmd(base_app, 'history') verify_hi_last_result(base_app, 0) (out, err) = run_cmd(base_app, 'history') assert (out == []) verify_hi_last_result(base_app, 0) run_cmd(base_app, 'help') (out, err) = run_cmd(base_app, 'history') expected = normaliz...
def test_receive_withdraw_request(): pseudo_random_generator = random.Random() (our_model1, _) = create_model(balance=70) (partner_model1, privkey2) = create_model(balance=100) signer = LocalSigner(privkey2) channel_state = create_channel_from_models(our_model1, partner_model1, privkey2) block_h...
def sdn_get_confusion(model, loader, confusion_stats, device='cpu'): model.eval() layer_correct = {} layer_wrong = {} instance_confusion = {} outputs = list(range(model.num_output)) for output_id in outputs: layer_correct[output_id] = set() layer_wrong[output_id] = set() with...
class ThrowerEnv(mujoco_env.MujocoEnv, utils.EzPickle): def __init__(self): utils.EzPickle.__init__(self) self._ball_hit_ground = False self._ball_hit_location = None mujoco_env.MujocoEnv.__init__(self, 'thrower.xml', 5) def _step(self, a): ball_xy = self.get_body_com('ba...
class InvertDict(dict): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._inverted_dict = dict() for (k, v) in self.items(): if (v in self._inverted_dict): raise GinoException('Column name {} already maps to {}'.format(v, self._inverted_...
def inside_not_trans(graph): id2node = {node['id']: node for node in graph['nodes']} parents = {} grabbed_objs = [] for edge in graph['edges']: if (edge['relation_type'] == 'INSIDE'): if (edge['from_id'] not in parents): parents[edge['from_id']] = [edge['to_id']] ...
_dataframe_method _alias(smiles_col='smiles_column_name', mols_col='mols_column_name') def smiles2mol(df: pd.DataFrame, smiles_column_name: Hashable, mols_column_name: Hashable, drop_nulls: bool=True, progressbar: Optional[str]=None) -> pd.DataFrame: valid_progress = ['notebook', 'terminal', None] if (progressb...
def download_scan_id(scan_id): command = ('python download-scannet.py -o . --id %s' % scan_id) to_download = ['.aggregation.json', '.txt', '_vh_clean_2.0.010000.segs.json', '_vh_clean_2.ply', '_vh_clean_2.labels.ply'] for filetype in to_download: os.system(((command + ' --type ') + filetype))
def test_next_transfer_pair(): block_number = BlockNumber(3) balance = TokenAmount(10) pseudo_random_generator = random.Random() payer_transfer = create(LockedTransferSignedStateProperties(amount=balance, initiator=HOP1, target=ADDR, expiration=BlockExpiration(50))) channels = make_channel_set([Nett...
.django_db def test_scope_keep_filter(site1, site2, post1, post2): with pytest.raises(ScopeError): Post.objects.all() with scope(site=site1): assert (list(Post.objects.annotate(c=Value(3, output_field=IntegerField())).distinct().all()) == [post1]) with scope(site=site2): assert (list...
_request_params(docs._observation_id, docs._access_token) def delete_observation(observation_id: int, **params): response = delete(url=f'{API_V0}/observations/{observation_id}.json', raise_for_status=False, **params) if (response.status_code == 404): raise ObservationNotFound(response=response) resp...
def test_relative_outdir(mocker, tmp_dir, package_test_flit): mocker.patch('pyproject_hooks.BuildBackendHookCaller', autospec=True) builder = build.ProjectBuilder(package_test_flit) builder._hook.build_sdist.return_value = 'dist.tar.gz' builder.build('sdist', '.') builder._hook.build_sdist.assert_ca...
class RandomCrop1dReturnCoordinates(RandomCrop): def forward(self, img: Image) -> (BoundingBox, Image): if (self.padding is not None): img = F.pad(img, self.padding, self.fill, self.padding_mode) (width, height) = get_image_size(img) if (self.pad_if_needed and (width < self.size[...
def onrun_antlr4(unit, *args): unit.onexternal_resource(['ANTLR4', ('sbr:' + ANTLR4_RESOURCE_ID)]) if (len(args) < 1): raise Exception('Not enough arguments for RUN_ANTLR4 macro') arg_list = ['-jar', ('${ANTLR4}/' + ANTLR4_JAR_PATH)] arg_list += list(args) unit.set(['ANTLR4', '$(ANTLR4)']) ...
class SawyerPickOutOfHoleV2Policy(Policy): _fully_parsed def _parse_obs(obs): return {'hand_pos': obs[:3], 'gripper': obs[3], 'puck_pos': obs[4:7], 'goal_pos': obs[(- 3):], 'unused_info': obs[7:(- 3)]} def get_action(self, obs): o_d = self._parse_obs(obs) action = Action({'delta_pos'...
def test__loss_function(): data = pd.DataFrame({'1': [float(i) for i in range(1000)], '2': [float((2 * i)) for i in range(1000)]}) tvae = TVAESynthesizer(epochs=300) tvae.fit(data) num_samples = 1000 sampled = tvae.sample(num_samples) error = 0 for (_, row) in sampled.iterrows(): err...
class RightPoolFunction(Function): def forward(ctx, input): output = right_pool.forward(input)[0] ctx.save_for_backward(input) return output def backward(ctx, grad_output): input = ctx.saved_variables[0] output = right_pool.backward(input, grad_output)[0] return o...
class ExtractPythonTestCase(unittest.TestCase): def test_nested_calls(self): buf = BytesIO(b'msg1 = _(i18n_arg.replace(r\'"\', \'"\'))\nmsg2 = ungettext(i18n_arg.replace(r\'"\', \'"\'), multi_arg.replace(r\'"\', \'"\'), 2)\nmsg3 = ungettext("Babel", multi_arg.replace(r\'"\', \'"\'), 2)\nmsg4 = ungettext(i18...
def test_direct_junction_offsets_suc_suc_1_right_wrong_input(direct_junction_right_multi_lane_fixture): (main_road, small_road, junction_creator) = direct_junction_right_multi_lane_fixture main_road.add_predecessor(xodr.ElementType.junction, junction_creator.id) small_road.add_successor(xodr.ElementType.jun...
def runAllModulesOnEachHost(args): if (args['nmap-file'] != None): nmapReport = NmapParser.parse_fromfile(args['nmap-file']) for aHost in nmapReport.hosts: hostAdress = aHost.address for aService in aHost.services: serviceName = aService.service.lower() ...
def _get_tune_resources(num_actors: int, cpus_per_actor: int, gpus_per_actor: int, resources_per_actor: Optional[Dict], placement_options: Optional[Dict]): if TUNE_INSTALLED: from ray.tune import PlacementGroupFactory head_bundle = {} child_bundle = {'CPU': cpus_per_actor, 'GPU': gpus_per_ac...
class CharDropout(nn.Module): def __init__(self, p: float=0.0) -> None: super(CharDropout, self).__init__() self.p: float = p def forward(self, input: Tensor) -> Tensor: if ((self.p == 0.0) or (not self.training)): return input (batch, length, char_length, _) = input....
def add_file_handler(logger: logging.Logger, logging_level, log_dir: str, log_file_base_name: Optional[str]=''): abs_log_dir = (Path(get_starting_dir_abs_path()) / log_dir) abs_log_dir.mkdir(parents=True, exist_ok=True) log_file = get_formatted_filename(log_file_base_name, datetime.now(), 'txt') formatt...
class Protonet(nn.Module): def __init__(self, encoder): super(Protonet, self).__init__() self.encoder = encoder self.slf_attn = MultiHeadAttention(1, 512, 512, 512, dropout=0) def loss(self, sample, stage, eval=False): xs = Variable(sample['xs']) xq = Variable(sample['xq'...
def darknet53_body(inputs): def res_block(inputs, filters): shortcut = inputs net = conv2d(inputs, (filters * 1), 1) net = conv2d(net, (filters * 2), 3) net = (net + shortcut) return net net = conv2d(inputs, 32, 3, strides=1) net = conv2d(net, 64, 3, strides=2) ne...
def test_install_logs_output(tester: CommandTester, mocker: MockerFixture) -> None: assert isinstance(tester.command, InstallerCommand) mocker.patch.object(tester.command.installer, 'run', return_value=0) mocker.patch('poetry.masonry.builders.editable.EditableBuilder') tester.execute() assert (teste...
def test_families(): families = table.families() for (name, fdesc) in six.iteritems(families): assert isinstance(name, bytes) assert isinstance(fdesc, dict) assert ('name' in fdesc) assert isinstance(fdesc['name'], six.binary_type) assert ('max_versions' in fdesc)
def dataloader_impl(dataset: Dataset, batch_size: int, return_idx: bool=False, return_jnp_array: bool=False): batch_idx = np.arange(len(dataset)) steps_per_epoch = math.ceil((len(dataset) / batch_size)) batch_idx = np.array_split(batch_idx, steps_per_epoch) for idx in batch_idx: batch = dataset[...
def hexLat2W(nrows=5, ncols=5, **kwargs): if ((nrows == 1) or (ncols == 1)): print('Hexagon lattice requires at least 2 rows and columns') print('Returning a linear contiguity structure') return lat2W(nrows, ncols) n = (nrows * ncols) rid = [(i // ncols) for i in range(n)] cid = ...
class VGG(nn.Module): def __init__(self, features, num_classes=1000): super(VGG, self).__init__() self.features = features self.classifier = nn.Sequential(nn.Linear(((512 * 7) * 7), 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, num_cl...
def check_installed(required_solvers, install_dir, bindings_dir, mirror_link): pypath_solvers = get_env().factory.all_solvers() global_solvers_status = [] print('Installed Solvers:') for i in INSTALLERS: installer_ = i.InstallerClass(install_dir=install_dir, bindings_dir=bindings_dir, solver_ver...
class WallFillProperty(bpy.types.PropertyGroup): width: FloatProperty(name='Wall Width', min=get_scaled_unit(0.0), max=get_scaled_unit(100.0), default=get_scaled_unit(0.075), unit='LENGTH', description='Width of each wall') def draw(self, context, layout): row = layout.row(align=True) row.prop(s...
class Task2Dataset(BaseDataset): def __getitem__(self, index) -> Tuple: (query_id, idx) = self.samples[index] product_id = self.database[self.split_dataset][query_id]['product_id'][idx] example_id = self.database[self.split_dataset][query_id]['example_id'][idx] dataset = torch.tensor...
_bitsandbytes _accelerate _torch _torch_gpu class MixedInt8T5Test(unittest.TestCase): def setUpClass(cls): cls.model_name = 't5-small' cls.dense_act_model_name = 'google/flan-t5-small' cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) cls.input_text = 'Translate in German...
class DiscriminatorSTFT(nn.Module): def __init__(self, filters: int, in_channels: int=1, out_channels: int=1, n_fft: int=1024, hop_length: int=256, win_length: int=1024, max_filters: int=1024, filters_scale: int=1, kernel_size: tp.Tuple[(int, int)]=(3, 9), dilations: tp.List=[1, 2, 4], stride: tp.Tuple[(int, int)]=...
def path_deploy(base, port=0, host='', index=True, static_dir=None, reconnect_timeout=0, cdn=True, debug=False, allowed_origins=None, check_origin=None, max_payload_size='200M', **tornado_app_settings): debug = Session.debug = os.environ.get('PYWEBIO_DEBUG', debug) page.MAX_PAYLOAD_SIZE = max_payload_size = par...
class TestCopyArea(EndianTest): def setUp(self): self.req_args_0 = {'dst_drawable': , 'dst_x': (- 27552), 'dst_y': (- 6968), 'gc': , 'height': 7340, 'src_drawable': , 'src_x': (- 24637), 'src_y': (- 24026), 'width': 46214} self.req_bin_0 = b'>\x00\x07\x00c\xa6\x9an\x86]\x17^5\xa2\xc7g\xc3\x9f&\xa2`\...
def main(client, config): (store_sales, date_dim, store, product_reviews) = benchmark(read_tables, config=config, compute_result=config['get_read_time']) q18_startDate_int = np.datetime64(q18_startDate, 'ms').astype(int) q18_endDate_int = np.datetime64(q18_endDate, 'ms').astype(int) date_dim_filtered = ...
class DescribeZeroOrOne(): def it_adds_a_getter_property_for_the_child_element(self, getter_fixture): (parent, zooChild) = getter_fixture assert (parent.zooChild is zooChild) def it_adds_an_add_method_for_the_child_element(self, add_fixture): (parent, expected_xml) = add_fixture ...
class FittingViewDrop(wx.DropTarget): def __init__(self, dropFn, *args, **kwargs): super(FittingViewDrop, self).__init__(*args, **kwargs) self.dropFn = dropFn self.dropData = wx.TextDataObject() self.SetDataObject(self.dropData) def OnData(self, x, y, t): if self.GetData(...
def test_variables__validate_dims_optional(): spec = ArrayLikeSpec('foo', 'foo doc', kind='i', dims=({None, 'windows', 'variants'}, 'samples', 'ploidy')) ds = xr.Dataset() ds['valid_0'] = (('samples', 'ploidy'), np.ones((2, 3), int)) ds['valid_1'] = (('windows', 'samples', 'ploidy'), np.ones((1, 2, 3), ...
class Index(Op): __props__ = () def make_node(self, x, elem): assert isinstance(x.type, TypedListType) assert (x.ttype == elem.type) return Apply(self, [x, elem], [scalar()]) def perform(self, node, inputs, outputs): (x, elem) = inputs (out,) = outputs for y i...
def test_pipeline(root_path): opt = parse_options(root_path, is_train=False) torch.backends.cudnn.benchmark = True make_exp_dirs(opt) log_file = osp.join(opt['path']['log'], f"test_{opt['name']}_{get_time_str()}.log") logger = get_root_logger(logger_name='basicsr', log_level=logging.INFO, log_file=l...
class GeneralizedRCNN(nn.Module): def __init__(self, cfg): super(GeneralizedRCNN, self).__init__() self.backbone = build_backbone(cfg) self.rpn = build_rpn(cfg) self.roi_heads = build_roi_heads(cfg) def forward(self, images, targets=None): if (self.training and (targets i...
def infixNotation(baseExpr, opList, lpar=Suppress('('), rpar=Suppress(')')): class _FB(FollowedBy): def parseImpl(self, instring, loc, doActions=True): self.expr.tryParse(instring, loc) return (loc, []) ret = Forward() lastExpr = (baseExpr | ((lpar + ret) + rpar)) for (i,...
def save_images(webpage, visuals, image_path, aspect_ratio=1.0, width=256): image_dir = webpage.get_image_dir() short_path = ntpath.basename(image_path[0]) name = os.path.splitext(short_path)[0] webpage.add_header(name) (ims, txts, links) = ([], [], []) for (label, im_data) in visuals.items(): ...
def get_criterion(opt, summarywriter=None): assert isinstance(opt['crit'], list) crit_objects = [] for item in opt['crit']: crit_name = item.lower() if (crit_name == 'lang'): this_crit_object = LanguageGeneration(opt, crit_name) elif (crit_name == 'length'): t...
def usage(): printerr('Usage is: export-to-postgresql.py <database name> [<columns>] [<calls>] [<callchains>] [<pyside-version-1>]') printerr("where: columns 'all' or 'branches'") printerr(" calls 'calls' => create calls and call_paths table") printerr(" callchains...
class SIGN(Frame): _framespec = [ByteSpec('group', default=128), BinaryDataSpec('sig')] def HashKey(self): return ('%s:%s:%s' % (self.FrameID, self.group, _bytes2key(self.sig))) def __bytes__(self): return self.sig def __eq__(self, other): return (self.sig == other) __hash__ ...
class F9_TestCase(FC6_TestCase): def runTest(self): FC6_TestCase.runTest(self) self.assert_removed('vnc', 'connect') self.assert_parse_error('vnc --host=HOSTNAME --connect=HOSTNAME --password=PASSWORD') self.assert_parse_error('vnc --host=HOSTNAME --connect=HOSTNAME --password=PASSWO...
class Carousel(Widget): def __init__(self, view, css_id, show_indicators=True, interval=5000, pause='hover', wrap=True, keyboard=True, min_height=None): super().__init__(view) self.carousel_panel = self.add_child(Div(view, css_id=css_id)) self.carousel_panel.append_class('carousel') ...
def violet(N, state=None): state = (np.random.RandomState() if (state is None) else state) uneven = (N % 2) X = (state.randn((((N // 2) + 1) + uneven)) + (1j * state.randn((((N // 2) + 1) + uneven)))) S = np.arange(len(X)) y = irfft((X * S)).real if uneven: y = y[:(- 1)] return norma...
def test_remove_overridden_styles(): from typing import List from cmd2 import Bg, EightBitBg, EightBitFg, Fg, RgbBg, RgbFg, TextStyle def make_strs(styles_list: List[ansi.AnsiSequence]) -> List[str]: return [str(s) for s in styles_list] styles_to_parse = make_strs([Fg.BLUE, TextStyle.UNDERLINE_D...