code
stringlengths
281
23.7M
class TestCAlgorithms(unittest.TestCase): def test_get_julian_day_from_gregorian(self): self.assertRaises(ValueError, alg_p.get_julian_day_from_gregorian_date, 2016, 2, 30) self.assertRaises(ValueError, alg_p.get_julian_day_from_gregorian_date, 2015, 2, 29) self.assertRaises(ValueError, alg_...
def test_set_size_custom() -> None: instance = printer.Dummy() instance.set_with_default(custom_size=True, width=8, height=7) expected_sequence = (TXT_SIZE, bytes(((TXT_STYLE['width'][8] + TXT_STYLE['height'][7]),)), TXT_STYLE['flip'][False], TXT_STYLE['smooth'][False], TXT_STYLE['bold'][False], TXT_STYLE['...
def recursive_render(template_dir: Path, environment: Environment, _root_dir: (str | os.PathLike[str])='.') -> list[str]: rendered_paths: list[str] = [] for (root, file) in ((Path(root), file) for (root, _, files) in os.walk(template_dir) for file in files if ((not any((elem.startswith('.') for elem in Path(roo...
class Bookmark(): def for_widget(cls, description, query_arguments=None, **bookmark_kwargs): return Bookmark('', '', description, query_arguments=query_arguments, ajax=True, **bookmark_kwargs) def __init__(self, base_path, relative_path, description, query_arguments=None, ajax=False, detour=False, exact...
class WorkflowEnabledMeta(base.WorkflowEnabledMeta, models.base.ModelBase): def _find_workflows(mcs, attrs): workflows = {} for (k, v) in attrs.items(): if isinstance(v, StateField): workflows[k] = v return workflows def _add_workflow(mcs, field_name, state_fi...
class QtHandler(QtHandlerBase): pin_signal = pyqtSignal(object, object) def __init__(self, win, pin_matrix_widget_class, device): super(QtHandler, self).__init__(win, device) self.pin_signal.connect(self.pin_dialog) self.pin_matrix_widget_class = pin_matrix_widget_class def get_pin(s...
class DialogSelectTrack(SimpleBuilderApp): def __init__(self, data_path=None, tracks=None, okmethod=None, gpx=None): logging.debug('>>') self.okmethod = okmethod self.tracks = tracks self.gpx = gpx SimpleBuilderApp.__init__(self, 'selecttrackdialog.ui') logging.debug(...
def HeronFit(DB, Gamedata, Saveddata): print('Creating Heron - RemoteSebo') item = DB['gamedata_session'].query(Gamedata['Item']).filter((Gamedata['Item'].name == 'Heron')).first() ship = Saveddata['Ship'](item) fit = Saveddata['Fit'](ship, 'Heron - RemoteSebo') mod = Saveddata['Module'](DB['db'].ge...
def _wait_for_condition(self, condition=None, timeout=None, poll_frequency=0.5, ignored_exceptions=None): condition = functools.partial((condition or self.visit_condition), self) timeout = (timeout or self.wait_time) return wait.WebDriverWait(self.driver, timeout, poll_frequency=poll_frequency, ignored_exce...
class Ui_MainWindow(QtWidgets.QMainWindow): def __init__(self): super(Ui_MainWindow, self).__init__() def setupUi(self, MainWindow): MainWindow.setObjectName('MainWindow') MainWindow.setEnabled(True) MainWindow.resize(1000, 650) self.centralwidget = QtWidgets.QWidget(Main...
def format_version(version: ScmVersion) -> str: log.debug('scm version %s', version) log.debug('config %s', version.config) if version.preformatted: assert isinstance(version.tag, str) return version.tag main_version = _entrypoints._call_version_scheme(version, 'setuptools_scm.version_sc...
def prepare_class_def(path: str, module_name: str, cdef: ClassDef, errors: Errors, mapper: Mapper) -> None: ir = mapper.type_to_ir[cdef.info] info = cdef.info attrs = get_mypyc_attrs(cdef) if (attrs.get('allow_interpreted_subclasses') is True): ir.allow_interpreted_subclasses = True if (attr...
class SpatialGroupEnhance(nn.Module): def __init__(self, groups): super().__init__() self.groups = groups self.avg_pool = nn.AdaptiveAvgPool2d(1) self.weight = nn.Parameter(torch.zeros(1, groups, 1, 1)) self.bias = nn.Parameter(torch.zeros(1, groups, 1, 1)) self.sig =...
def import_gmsh_mesh(filename, analysis=None): assert (filename[(- 4):] == u'.geo') mesh_filename = (filename[:(- 4)] + u'.unv') cmdlist = [u'gmsh', u'-format', u'unv', filename, u'-o', mesh_filename, u'-'] error = _run_command(cmdlist) if (not error): if analysis: docName = anal...
def create_straight_road(road_id, length=100, junction=(- 1), n_lanes=1, lane_offset=3): warn('create_straight_road should not be used anymore, please use the create_road function instead', DeprecationWarning, 2) line1 = Line(length) planview1 = PlanView() planview1.add_geometry(line1) lanesec1 = La...
class ResponseProcessingOpener(OpenerDirector): def open(self, fullurl, data=None, timeout=_sockettimeout._GLOBAL_DEFAULT_TIMEOUT): def bound_open(fullurl, data=None, timeout=_sockettimeout._GLOBAL_DEFAULT_TIMEOUT): return OpenerDirector.open(self, fullurl, data, timeout) return wrapped_...
class PascalVocGenerator(Generator): def __init__(self, data_dir, set_name, classes=voc_classes, image_extension='.jpg', skip_truncated=False, skip_difficult=False, **kwargs): self.data_dir = data_dir self.set_name = set_name self.classes = classes self.image_names = [l.strip().split...
class Scheduler(abc.ABC, Generic[T]): def __init__(self, backend: str, session_name: str) -> None: self.backend = backend self.session_name = session_name def close(self) -> None: pass def submit(self, app: AppDef, cfg: T, workspace: Optional[str]=None) -> str: resolved_cfg =...
def test_expand_multiple_levels(df_expand): expected = df_expand.pivot_wider('id', ('year', 'gender'), 'percentage', names_expand=True, flatten_levels=False) actual = df_expand.complete('year', 'gender', 'id').pivot(index='id', columns=('year', 'gender'), values='percentage') assert_frame_equal(actual, expe...
class BarthezConverter(SpmConverter): def unk_id(self, proto): unk_id = 3 return unk_id def post_processor(self): return processors.TemplateProcessing(single='<s> $A </s>', pair='<s> $A </s> </s> $B </s>', special_tokens=[('<s>', self.original_tokenizer.convert_tokens_to_ids('<s>')), ('<...
def confirm_team_invite(code, user_obj): found = find_matching_team_invite(code, user_obj) code_found = False for invite in find_organization_invites(found.team.organization, user_obj): try: code_found = True add_user_to_team(user_obj, invite.team) except UserAlreadyI...
class SignUp(): async def sign_up(self: 'pyrogram.Client', phone_number: str, phone_code_hash: str, first_name: str, last_name: str='') -> 'types.User': phone_number = phone_number.strip(' +') r = (await self.invoke(raw.functions.auth.SignUp(phone_number=phone_number, first_name=first_name, last_nam...
class Solution(): def checkPossibility(self, nums: List[int]) -> bool: n = len(nums) if ((n == 1) or (n == 2)): return True i = 0 nums1 = nums[:] while (i < (n - 1)): if (nums[i] <= nums[(i + 1)]): i += 1 continue ...
class TestNameCheckVisitor(TestNameCheckVisitorBase): _passes() def test_known_ordered(self): from typing_extensions import OrderedDict known_ordered = OrderedDict({1: 2}) bad_ordered = OrderedDict({'a': 'b'}) def capybara(arg: OrderedDict[(int, int)]) -> None: pass ...
.parametrize('stream', ['stdout', 'stderr']) def test_exit_successful_output(qtbot, proc, py_proc, stream): with qtbot.wait_signal(proc.finished, timeout=10000): proc.start(*py_proc('\n import sys\n print("test", file=sys.{})\n sys.exit(0)\n '.format(stream)))
def test_custom_css(pytester, css_file_path, expandvar): result = run(pytester, 'report.html', cmd_flags=['--css', expandvar, '--css', 'two.css']) result.assert_outcomes(passed=1) path = pytester.path.joinpath('assets', 'style.css') with open(str(path)) as f: css = f.read() assert_that(c...
def average(dj_init=None, img_db=None, djs_file=None, avgs_file=None, pcas_file=None, op=None): djs = load_dict(op['data_checkpoint']) avgs = load_dict(op['average']['checkpoint']) if ((- 1) not in djs): assert (len(djs) == 0) djs[(- 1)] = dj_init AIF.pickle_dump(djs, op['data_checkp...
class Trainer(): def __init__(self, G, D, latent_size, dataset, device, Gs=None, Gs_beta=(0.5 ** (32 / 10000)), Gs_device=None, batch_size=32, device_batch_size=4, label_size=0, data_workers=4, G_loss='logistic_ns', D_loss='logistic', G_reg='pathreg:2', G_reg_interval=4, G_opt_class='Adam', G_opt_kwargs={'lr': 0.00...
def main(args): print(args) split_name = ('dev' if args.dev else 'train') dataset_break = DatasetBreak(args.qdmr_path, split_name) dataset_spider = DatasetSpider(args.spider_path, split_name) if args.input_grounding: partial_grounding = load_grounding_from_file(args.input_grounding) else...
class AlgorithmSummary(): algorithm_qubits: float = _PRETTY_FLOAT measurements: float = _PRETTY_FLOAT t_gates: float = _PRETTY_FLOAT toffoli_gates: float = _PRETTY_FLOAT rotation_gates: float = _PRETTY_FLOAT rotation_circuit_depth: float = _PRETTY_FLOAT def __mul__(self, other: int) -> 'Algo...
class JSONFormatter(logging.Formatter): def __init__(self, fmt=None, datefmt=None): self.datefmt = datefmt def formatException(self, ei, strip_newlines=True): lines = traceback.format_exception(*ei) if strip_newlines: lines = [itertools.ifilter((lambda x: x), line.rstrip().sp...
class InferGroupedEmbeddingsLookup(InferGroupedLookupMixin, BaseEmbeddingLookup[(KJTList, List[torch.Tensor])], TBEToRegisterMixIn): def __init__(self, grouped_configs_per_rank: List[List[GroupedEmbeddingConfig]], world_size: int, fused_params: Optional[Dict[(str, Any)]]=None, device: Optional[torch.device]=None) -...
class WeightedLottery(Generic[T]): def __init__(self, items: Iterable[T], weight_key: Callable[([T], int)]): self.weights: List[int] = [] self.items = list(items) if (not self.items): raise ValueError('items must not be empty') accumulated_weight = 0 for item in s...
.parametrize('username,password', users) .parametrize('project_id', projects) .parametrize('membership_id', memberships) def test_detail(db, client, username, password, project_id, membership_id): client.login(username=username, password=password) membership = Membership.objects.filter(project_id=project_id, id...
class _NeuralNetwork(NeuralNetwork): def _forward(self, input_data, weights): batch_size = (input_data.shape[0] if (input_data is not None) else 1) return np.zeros((batch_size, *self.output_shape)) def _backward(self, input_data, weights): input_grad = None batch_size = (input_da...
def test_create_hints_item_joke(empty_patches, players_config): asset_id = 1000 (logbook_node, _, region_list) = _create_region_list(asset_id, PickupIndex(50)) patches = dataclasses.replace(empty_patches, hints={region_list.identifier_for_node(logbook_node): Hint(HintType.JOKE, None)}) rng = MagicMock()...
def test_delete_existing_proposal_by_different_author(settings, login, conferences): client = login[0] conference = conferences['future'] section = conference.proposal_sections.all()[0] proposal_type = conference.proposal_types.all()[0] user = f.create_user() proposal = f.create_proposal(confere...
.parametrize('density,expected', [(0, ((- 1684649.41338), (- 350356.81377), 1684649.41338, 2234551.18559)), (100, ((- 1684649.41338), (- ), 1684649.41338, 2234551.18559))]) def test_transform_bounds_densify(density, expected): transformer = Transformer.from_crs('EPSG:4326', '+proj=laea +lat_0=45 +lon_0=-100 +x_0=0 ...
class BucketTestCase(unittest.TestCase): q = Auth(access_key, secret_key) bucket = BucketManager(q) def test_list(self): (ret, eof, info) = self.bucket.list(bucket_name, limit=4) assert (eof is False) assert (len(ret.get('items')) == 4) (ret, eof, info) = self.bucket.list(buc...
def loss(logits, labels): cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits) cross_entropy_mean = tf.reduce_mean(cross_entropy) regularization_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) loss_ = tf.add_n(([cross_entropy_mean] + regularization_...
class Env(): total_cards = sorted(((to_char(np.arange(3, 16)) * 4) + ['*', '$']), key=(lambda k: Card.cards_to_value[k])) def __init__(self, agent_names=('agent1', 'agent2', 'agent3')): seed = ((id(self) + int(datetime.now().strftime('%Y%m%d%H%M%S%f'))) % ) np.random.seed(seed) self.agen...
def _expr(expr): node = type(expr) if (node is ast.Name): return _build_atomic(expr.id) if (node is ast.Call): args = _parse_args(expr.args) kwargs = _parse_kwargs(expr.keywords) return _build_predicate(expr.func.id, args, kwargs) if (node is ast.Subscript): field...
def test_L1_bits_connection(): a = CaseConnectBitsConstToOutComp.DUT() a.elaborate() a.apply(StructuralRTLIRGenL1Pass(gen_connections(a))) connections = a.get_metadata(StructuralRTLIRGenL1Pass.connections) comp = sexp.CurComp(a, 's') assert (connections == [(sexp.ConstInstance(Bits32(0), 0), sex...
def is_ast_cont_with_surrounding_lambda(k): from pycket import interpreter as i cs = [i.LetCont, i.LetrecCont, i.BeginCont, i.Begin0Cont, i.Begin0BodyCont, i.WCMKeyCont, i.WCMValCont] for c in cs: if isinstance(k, c): a = k.get_ast() if (isinstance(a, i.AST) and a.surrounding...
_torch class TestTrainerExt(TestCasePlus): def run_seq2seq_quick(self, distributed=False, extra_args_str=None, predict_with_generate=True, do_train=True, do_eval=True, do_predict=True): output_dir = self.run_trainer(eval_steps=1, max_len=12, model_name=MBART_TINY, num_train_epochs=1, distributed=distributed...
def resnet_retinanet(num_classes, backbone='resnet50', modifier=None, **kwargs): inputs = keras.layers.Input(shape=(None, None, 3)) if (backbone == 'resnet50'): resnet = keras_resnet.models.ResNet50(inputs, include_top=False, freeze_bn=True) elif (backbone == 'resnet101'): resnet = keras_res...
def test_it_cannot_solve_other_solver_errors() -> None: from poetry.mixology.solutions.providers import PythonRequirementSolutionProvider incompatibility = Incompatibility([Term(Dependency('foo', '^1.0'), True)], NoVersionsCause()) exception = SolverProblemError(SolveFailure(incompatibility)) provider =...
def test_dynamic_property_values_update_in_one_instance_leaves_other_unchanged(): generic1 = FakeBase() generic2 = FakeBase() generic1.fake_ctrl_values = (0, 33) generic1.fake_ctrl = 50 generic2.fake_ctrl = 50 assert (generic1.fake_ctrl == 33) assert (generic2.fake_ctrl == 10)
class ModelFormTagFieldOptionsTest(TagTestManager, TestCase): manage_models = [test_models.TagFieldOptionsModel] def setUpExtra(self): self.form = test_forms.TagFieldOptionsModelForm self.model = test_models.TagFieldOptionsModel _if_mysql def test_case_sensitive_true(self): tag_m...
class MessageBroker(): def __init__(self, stage): self.stage = stage self._messages = [] def broadcast(self, message): self._messages.append(message) def get_messages(self): return self._messages def mark_completed(self): self._messages.clear()
def events_for_close(channel_state: NettingChannelState, block_number: BlockNumber, block_hash: BlockHash) -> List[Event]: events: List[Event] = [] if (get_status(channel_state) in CHANNEL_STATES_PRIOR_TO_CLOSED): channel_state.close_transaction = TransactionExecutionStatus(block_number, None, None) ...
def make_migration(name): try: with Capturing() as output: call_command('makemigrations', '--name={}'.format(name), app_name, verbosity=0) except Exception as e: print('>> makemigration failed for {}:'.format(name)) print('\n'.join(output)) print('') raise e ...
class LetsuploadCo(SimpleDownloader): __name__ = 'LetsuploadCo' __type__ = 'downloader' __version__ = '0.03' __status__ = 'testing' __pattern__ = ' __config__ = [('enabled', 'bool', 'Activated', True), ('use_premium', 'bool', 'Use premium account if available', True), ('fallback', 'bool', 'Fallb...
def find_executable_batch_size(function: callable=None, starting_batch_size: int=128, auto_find_batch_size: bool=False): if (function is None): return functools.partial(find_executable_batch_size, starting_batch_size=starting_batch_size, auto_find_batch_size=auto_find_batch_size) if auto_find_batch_size...
def nearest_unequal_elements(dts, dt): if (not dts.is_unique): raise ValueError('dts must be unique') if (not dts.is_monotonic_increasing): raise ValueError('dts must be sorted in increasing order') if (not len(dts)): return (None, None) sortpos = dts.searchsorted(dt, side='left'...
class CoTAttention(nn.Module): def __init__(self, dim=512, kernel_size=3): super().__init__() self.dim = dim self.kernel_size = kernel_size self.key_embed = nn.Sequential(nn.Conv2d(dim, dim, kernel_size=kernel_size, padding=(kernel_size // 2), groups=4, bias=False), nn.BatchNorm2d(di...
def inherit_signature(c, method_name): m = getattr(c, method_name) sig = inspect.signature(m) params = [] for param in sig.parameters.values(): if ((param.name == 'self') or (param.annotation is not param.empty)): params.append(param) continue for ancestor in insp...
def form_loads(explode: bool, name: str, schema_type: str, location: Mapping[(str, Any)]) -> Any: explode_type = (explode, schema_type) if (explode_type == (False, 'array')): return split(location[name], separator=',') elif (explode_type == (True, 'array')): if (name not in location): ...
.parametrize('available', [True, False]) def test_is_available(available, mocker): mock = mocker.patch.object(pdfjs, 'get_pdfjs_res', autospec=True) if available: mock.return_value = b'foo' else: mock.side_effect = pdfjs.PDFJSNotFound('build/pdf.js') assert (pdfjs.is_available() == avail...
class AttrVI_ATTR_GPIB_ATN_STATE(EnumAttribute): resources = [(constants.InterfaceType.gpib, 'INTFC')] py_name = 'atn_state' visa_name = 'VI_ATTR_GPIB_ATN_STATE' visa_type = 'ViInt16' default = NotAvailable (read, write, local) = (True, False, False) enum_type = constants.LineState
class TestOptionMarker(): .options(debug=False) def test_not_debug_app(self, app): assert (not app.debug), 'Ensure the app not in debug mode' .options(foo=42) def test_update_application_config(self, request, app, config): assert (config['FOO'] == 42) def test_application_config_tear...
def create_strategy(name=None): import logging from bonobo.execution.strategies.base import Strategy if isinstance(name, Strategy): return name if (name is None): name = DEFAULT_STRATEGY logging.debug('Creating execution strategy {!r}...'.format(name)) try: factory = STRA...
def create_table(table: str, namespace: Optional[str]=None, catalog: Optional[str]=None, lifecycle_state: Optional[LifecycleState]=None, schema: Optional[Union[(pa.Schema, str, bytes)]]=None, schema_consistency: Optional[Dict[(str, SchemaConsistencyType)]]=None, partition_keys: Optional[List[Dict[(str, Any)]]]=None, pr...
class CudaRNGStatesTracker(): def __init__(self): self.states_ = {} self.seeds_ = set() def reset(self): self.states_ = {} self.seeds_ = set() def get_states(self): states = {} for name in self.states_: states[name] = self.states_[name] ret...
def set_werkzeug_hostname(f): (f) def wrapper(*args, **kwargs): try: hostname = json.loads(request.form['data'])['hostname'] except Exception: hostname = None ret = f(*args, **kwargs) if hostname: request.environ['REMOTE_ADDR'] = hostname ...
class MrpcPVP(PVP): VERBALIZER = {'0': ['Alas'], '1': ['Rather']} def get_parts(self, example: InputExample) -> FilledPattern: text_a = self.shortenable(example.text_a) text_b = self.shortenable(example.text_b) if (self.pattern_id == 1): string_list_a = [text_a, '.', self.mas...
class TestNFP(unittest.TestCase): def test_enviar(self): client = SoapClient(wsdl=WSDL, soap_ns='soap12env') client['Autenticacao'] = SimpleXMLElement((HEADER_XML % ('user', 'password', 'fed_tax_num', 1))) response = client.Enviar(NomeArquivo='file_name', ConteudoArquivo='content', EnvioNorm...
class ReplayBuffer(): def __init__(self, max_size=50): assert (max_size > 0), 'Empty buffer or trying to create a black hole. Be careful.' self.max_size = max_size self.data = [] def push_and_pop(self, data): to_return = [] for element in data.data: element = ...
class PororoStoryDataset(Dataset): def __init__(self, args, split, tokenizer): self.args = args self.root = args.dataset_dir self.feature_extractor = utils.get_feature_extractor_for_model(args.visual_model, image_size=args.image_size, train=False) self.image_size = args.image_size ...
def train_ubr_model(ubr_training_monitor, epoch_num, sess, eval_iter_num, taker, lr, train_batch_size, rec_model, ubr_model, target_train_file, user_feat_dict_file, item_feat_dict_file, context_dict_file, summary_writer, step, b_num): loss_step = [] reward_step = [] for i in range(epoch_num): data_l...
class LinesToReadline(): def __init__(self, lines, start): self.lines = lines self.current = start def readline(self): if (self.current <= self.lines.length()): self.current += 1 return (self.lines.get_line((self.current - 1)) + '\n') return '' def __c...
def get_latest_checkpoint(directory: pathlib.PosixPath, args: argparse.Namespace): latest_checkpoint = None checkpoint_files = list(directory.glob(f'*{args.checkpoint_id_pattern}*')) if checkpoint_files: latest_checkpoint = 0 for checkpoint_file in checkpoint_files: checkpoint_fi...
def register_dataframe_method(method): def inner(*args, **kwargs): class AccessorMethod(): def __init__(self, pyspark_obj): self._obj = pyspark_obj (method) def __call__(self, *args, **kwargs): return method(self._obj, *args, **kwargs) ...
def export_quant_table(quantizers: dict, quant_dir: str, format: str='toml'): table = {} def save_tensor(name: str, tensor): np.save(os.path.join(quant_dir, name), tensor.numpy()) return '{}.npy'.format(name) for (key, value) in quantizers.items(): quantizer = value[0] dump =...
def test_allows_post_releases_with_post_and_local_min() -> None: one = Version.parse('3.0.0+local.1') two = Version.parse('3.0.0-1') three = Version.parse('3.0.0-1+local.1') four = Version.parse('3.0.0+local.2') assert (not VersionRange(min=one, include_min=True).allows(two)) assert VersionRange...
def main(): min_cost_flow = pywrapgraph.SimpleMinCostFlow() start_nodes = (([0, 0, 0, 0] + [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]) + [5, 6, 7, 8]) end_nodes = (([1, 2, 3, 4] + [5, 6, 7, 8, 5, 6, 7, 8, 5, 6, 7, 8, 5, 6, 7, 8]) + [9, 9, 9, 9]) capacities = (([1, 1, 1, 1] + [1, 1, 1, 1, 1, 1, 1, ...
class TerminalView(View): def __init__(self, app): super().__init__(app) def cleanup(self): print('Goodbye') def print(self, txt): if txt: print('\x1b[92m{}\x1b[39m'.format(txt)) def detail(self, txt): print(txt) def error(self, e): if (not e): ...
def test_invalid_next_name_ignored(): packet = b'\x00\x00\x00\x00\x00\x01\x00\x02\x00\x00\x00\x00\x07Android\x05local\x00\x00\xff\x00\x01\xc0\x0c\x00/\x00\x01\x00\x00\x00x\x00\x08\xc02\x00\\x00\x00\x08\xc0\x0c\x00\x01\x00\x01\x00\x00\x00x\x00\x04\xc0\xa8X<' parsed = r.DNSIncoming(packet) assert (len(parsed....
def inference_detector(model, imgs): if isinstance(imgs, (list, tuple)): is_batch = True else: imgs = [imgs] is_batch = False cfg = model.cfg device = next(model.parameters()).device if isinstance(imgs[0], np.ndarray): cfg = cfg.copy() cfg.data.test.pipeline[0...
class NPMRole(Role): time_format = '%d-%m-%y %H:%M:%S' key = 'npm-up-to-date' def provision(self): self.provision_role(NodeJsRole) def is_package_installed(self, package_name, version=None): with settings(warn_only=True): if version: package_name = ('%%s' % (p...
def upsampleG(fieldmap, activation_data, shape=None): (offset, size, step) = fieldmap input_count = activation_data.shape[0] if (shape is None): shape = upsampled_shape(fieldmap, activation_data.shape[1:]) activations = numpy.zeros(((input_count,) + shape)) activations[((slice(None),) + cent...
def tokenize_stories(stories, add_speaker): (total_count, avg_sum_len, avg_context_len, avg_sum_sent, avg_context_sent) = (0, 0.0, 0.0, 0.0, 0.0) speaker_count = {} with open(stories, 'r') as f: data = json.load(f) processed_data = [] for sample in data: total_count += 1 sum ...
def test_class_method_inherited() -> None: nodes_ = builder.extract_node('\n class A:\n \n def method(cls):\n return cls\n\n class B(A):\n pass\n\n A().method() #\n A.method() #\n\n B().method() #\n B.method() #\n ') expected_names = ['A', 'A', 'B', 'B'] ...
def get_args(): parser = argparse.ArgumentParser(description='This script creates the\n text form of a subword lexicon FST to be compiled by fstcompile using\n the appropriate symbol tables (phones.txt and words.txt). It will mostly\n be invoked indirectly via utils/prepare_lang_subword.sh. The...
def main(): global FLAGS with open(FLAGS.cluster_spec_file, 'r') as fp: cluster_spec_str = json.load(fp) config = tf.ConfigProto() if (FLAGS.job_name == 'ps'): config.inter_op_parallelism_threads = 768 config.intra_op_parallelism_threads = 0 config.device_count['GPU'] = 0...
class App(models.Model): module = models.CharField(max_length=100, unique=True) active = models.BooleanField(default=False) class Meta(): app_label = 'rapidsms' def __str__(self): return self.module def __repr__(self): return ('<%s: %s>' % (type(self).__name__, self))
class TestHypenation(unittest.TestCase): def test_hypenation(self): assert (hyphenation('begegnen', Hyphenator('de_DE')) == ['be', 'geg', 'nen']) assert (hyphenation(".b,e~g'eg*nen, ", Hyphenator('de_DE')) == ['.b,e', "~g'eg", '*nen, ']) assert (hyphenation('Abend, ', Hyphenator('de_AT')) ==...
class VGG(tf.keras.Model): def __init__(self, vgg_name, num_classes, weight_decay): super(VGG, self).__init__() self.vgg_name = vgg_name self.num_classes = num_classes self.wd = weight_decay self.convlayers = self._make_convlayers(cfg[vgg_name]) self.fc_layers = self....
_module() class RawframeDataset(BaseDataset): def __init__(self, ann_file, pipeline, data_prefix=None, test_mode=False, filename_tmpl='img_{:05}.jpg', with_offset=False, multi_class=False, num_classes=None, start_index=1, modality='RGB'): self.filename_tmpl = filename_tmpl self.with_offset = with_of...
class VisaIOError(Error): def __init__(self, error_code: int) -> None: (abbreviation, description) = completion_and_error_messages.get(error_code, ('?', 'Unknown code.')) super(VisaIOError, self).__init__(('%s (%d): %s' % (abbreviation, error_code, description))) self.error_code = error_code...
class FixHasKey(fixer_base.BaseFix): BM_compatible = True PATTERN = "\n anchor=power<\n before=any+\n trailer< '.' 'has_key' >\n trailer<\n '('\n ( not(arglist | argument<any '=' any>) arg=any\n | arglist<(not argument<any '=' any>) arg=any ','>\n ...
class Conv1d(Mapper): def __init__(self, num_filters, filter_size, keep_probs, activation='relu'): self.keep_probs = keep_probs self.num_filters = num_filters self.filter_size = filter_size self.activation = activation def apply(self, is_train, x, mask=None): num_channels...
class KernelInclude(Include): def run(self): path = os.path.realpath(os.path.expandvars(self.arguments[0])) if path.startswith((os.sep + 'etc')): raise self.severe(('Problems with "%s" directive, prohibited path: %s' % (self.name, path))) self.arguments[0] = path return s...
def flatten_nested_unions(types: list[RType]) -> list[RType]: if (not any((isinstance(t, RUnion) for t in types))): return types flat_items: list[RType] = [] for t in types: if isinstance(t, RUnion): flat_items.extend(flatten_nested_unions(t.items)) else: flat...
class FeatureExtraction(torch.nn.Module): def __init__(self, train_fe=False, feature_extraction_cnn='vgg', normalization=True, last_layer='', use_cuda=True): super(FeatureExtraction, self).__init__() self.normalization = normalization if (feature_extraction_cnn == 'vgg'): self.mo...
class TagReader(): label2id_map = {'<START>': 0} def read_inst(cls, file, is_labeled, number, opinion_offset): insts = [] inputs = [] outputs = [] total_p = 0 original_p = 0 f = open(file, 'r', encoding='utf-8') for line in f: line = line.strip...
class Effect5486(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Medium Projectile Turret')), 'damageMultiplier', ship.getModifiedItemAttr('shipBonusMBC2'), skill='Minmatar Battlecruiser', **kwar...
def aggregate_results(filepaths: List[Path]) -> Dict[(str, Any)]: metrics = defaultdict(list) for f in filepaths: with f.open('r') as fd: data = json.load(fd) for (k, v) in data['results'].items(): metrics[k].append(v) agg = {k: np.mean(v) for (k, v) in metrics.items(...
class DeformRoIPoolFunction(Function): def symbolic(g, input, rois, offset, output_size, spatial_scale, sampling_ratio, gamma): return g.op('mmcv::MMCVDeformRoIPool', input, rois, offset, pooled_height_i=output_size[0], pooled_width_i=output_size[1], spatial_scale_f=spatial_scale, sampling_ratio_f=sampling_...
def test_dimensions_missing_params(): with pytest.raises(ValueError): calculate_default_transform('epsg:4326', 'epsg:3857', width=1, height=1, gcps=[1], resolution=1, dst_width=1, dst_height=None) with pytest.raises(ValueError): calculate_default_transform('epsg:4326', 'epsg:3857', width=1, heig...