code
stringlengths
281
23.7M
class Migration(migrations.Migration): dependencies = [('forum', '0002_auto__1626')] operations = [migrations.RemoveField(model_name='forum_plate', name='category_type'), migrations.RemoveField(model_name='forum_plate', name='code'), migrations.RemoveField(model_name='forum_plate', name='parent_category')]
def test_if1(evmtester, branch_results): evmtester.ifBranches(1, True, False, False, False) assert ([175, 176] in branch_results()[True]) evmtester.ifBranches(1, False, False, False, False) results = branch_results() assert ([175, 176] in results[False]) assert ([208, 209] in results[True])
class GradTTS(nn.Module): def __init__(self, model_config): super(GradTTS, self).__init__() self.diffusion = DIFFUSIONS.build(model_config.diffusion) if getattr(model_config, 'gradient_checkpointing', False): self.diffusion.denoise_fn.gradient_checkpointing_enable() def get_m...
def test_traverse_args(): provider1 = providers.Object('bar') provider2 = providers.Object('baz') provider = providers.Factory(list, 'foo', provider1, provider2) all_providers = list(provider.traverse()) assert (len(all_providers) == 2) assert (provider1 in all_providers) assert (provider2 i...
def extractKaede721WordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Hakata Tonkotsu Ramens', 'Hakata Tonkotsu Ramens', 'translated'), ('htr', 'Hakata Tonkotsu Ramen...
class table_features(loxi.OFObject): def __init__(self, table_id=None, command=None, features=None, name=None, metadata_match=None, metadata_write=None, capabilities=None, max_entries=None, properties=None): if (table_id != None): self.table_id = table_id else: self.table_id ...
class OptionPlotoptionsBulletSonificationContexttracksMappingTremoloDepth(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str)...
def test_compare_length(): data = encode([1, 2, 3, 4, 5]) assert (compare_length(data, 100) == (- 1)) assert (compare_length(data, 5) == 0) assert (compare_length(data, 1) == 1) data = encode([]) assert (compare_length(data, 100) == (- 1)) assert (compare_length(data, 0) == 0) assert (co...
class SnmprecRecordMixIn(object): def evaluateValue(self, oid, tag, value, **context): if (':' in tag): context['backdoor']['textTag'] = tag return (oid, '', value) else: return snmprec.SnmprecRecord.evaluate_value(self, oid, tag, value) def formatValue(self, ...
class Worksheet(): def __init__(self, workbook, title, xlrd_index=None, xlrd_sheet=None): self.title = title if (len(self.title) > MAX_LEN_WORKSHEET_TITLE): self.title = self.title[:MAX_LEN_WORKSHEET_TITLE] logging.warning(('Worksheet title > %d characters' % MAX_LEN_WORKSHEE...
class RegisterNamespaceRequest(betterproto.Message): name: str = betterproto.string_field(1) description: str = betterproto.string_field(2) owner_email: str = betterproto.string_field(3) workflow_execution_retention_period: timedelta = betterproto.message_field(4) clusters: List[v1replication.Cluste...
_packages_ns.route('/add/<ownername>/<projectname>/<package_name>/<source_type_text>') class PackageAdd(Resource): _api_login_required _packages_ns.doc(params=add_package_docs) _packages_ns.expect(package_add_input_model) _packages_ns.marshal_with(package_model) def post(self, ownername, projectname...
class TestMemoized(): def test_caching(self): return_value = True def some_function(arg): return return_value assert some_function(42) return_value = False assert some_function(42) def test_caching_different_args(self): return_value = True def ...
class TopicSubscriptionListView(LoginRequiredMixin, ListView): context_object_name = 'topics' model = Topic paginate_by = machina_settings.FORUM_TOPICS_NUMBER_PER_PAGE template_name = 'forum_member/subscription_topic_list.html' def get_queryset(self): return self.request.user.topic_subscript...
.parametrize('coords, expected_val', [pytest.param((10.0, 10.0), 0.0, id='(xori, yori)'), pytest.param((10.0, 20.0), 1.0, id='(xori, ymax)'), pytest.param((20.0, 10.0), 2.0, id='(xmax, yori)'), pytest.param((20.0, 20.0), 3.0, id='(xmax, ymax)'), pytest.param((15.0, 10.0), 1.0, id='((xori + xmax) / 2, yori)'), pytest.pa...
def dashboard(config, endpoint, view_func, rule='/'): app = Flask(__name__) app.add_url_rule(rule, endpoint=endpoint.name, view_func=(lambda : view_func)) flask_monitoringdashboard.bind(app, schedule=False) app.config['DEBUG'] = True app.config['TESTING'] = True with app.test_client() as client:...
class TestWealthCommandsPositive(AEATestCaseManyFlaky): .integration .flaky(reruns=MAX_FLAKY_RERUNS_INTEGRATION) def test_wealth_commands(self, password_or_none): agent_name = 'test_aea' self.create_agents(agent_name) self.set_agent_context(agent_name) self.generate_private_k...
class Result(object): def __init__(self): self.lock = Lock() self.lock.acquire() self.value = Exception() self.raised = False def put(self, value, raised): self.value = value self.raised = raised self.lock.release() def get(self): self.lock.acq...
class Solution(): def minCost(self, colors: str, neededTime: List[int]) -> int: prev = 0 cost = 0 for i in range(1, len(colors)): if (colors[i] == colors[prev]): if (neededTime[i] > neededTime[prev]): cost += neededTime[prev] ...
def extractBludeblobtranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, na...
def test_discourse_loader_load_post_with_invalid_post_id(discourse_loader, monkeypatch, caplog): def mock_get(*args, **kwargs): class MockResponse(): def raise_for_status(self): raise requests.exceptions.RequestException('Test error') return MockResponse() monkeypatch...
class FileRead(BaseTest): def setUp(self): session = SessionURL(self.url, self.password, volatile=True) modules.load_modules(session) self.run_argv = modules.loaded['file_read'].run_argv def test_read_php(self): self.assertEqual(self.run_argv(['test_file_read/ok.test']), b'OK') ...
def subscriber(topic: Topic) -> Callable[([SubscriberType], SubscriberType)]: def subscriber_wrapper(method: SubscriberType) -> SubscriberType: annotations = {arg: arg_type for (arg, arg_type) in method.__annotations__.items() if (arg not in ('self', 'return'))} if ((not (len(annotations) == 1)) or ...
.django_db def test_non_match_search_on_multiple_tas(client, monkeypatch, elasticsearch_award_index, award_with_tas): _setup_es(client, monkeypatch, elasticsearch_award_index) resp = query_by_tas(client, {'require': [_tas_path(ATA_TAS), _tas_path(BPOA_TAS)]}) assert (resp.json()['results'] == [])
class EventWatcher(metaclass=_Singleton): def __init__(self) -> None: self.target_list_lock: Lock = Lock() self.target_events_watch_data: Dict[(str, _EventWatchData)] = {} self._kill: bool = False self._has_started: bool = False self._watcher_thread = Thread(target=self._loop...
class TestAttributeOverrides(BaseTestCase): def test_template_name_override(self): create_instance(quantity=3) pk = Example.objects.all()[0].pk view = DetailView.as_view(model=Example, template_name='example.html') response = self.get(view, pk=pk) self.assertEqual(response.st...
def fetch_seek_paginator(query, kwargs, index_column, clear=False, count=None, cap=100): check_cap(kwargs, cap) model = index_column.parent.class_ (sort, hide_null, nulls_last) = (kwargs.get('sort'), kwargs.get('sort_hide_null'), kwargs.get('sort_nulls_last')) if sort: (query, sort_column) = sor...
def main(): global TOTAL_UPDATES global ITERATION_ESTIMATED_SECONDS with psycopg2.connect(dsn=CONNECTION_STRING) as connection: connection.autocommit = True connection.readonly = True if ((MIN_ID is None) or (MAX_ID is None)): with connection.cursor() as cursor: ...
def _install_dependencies(dependencies): if dependencies: log_path = os.path.join(paths.logs(), 'dependency.log') console.info(f"Installing track dependencies [{', '.join(dependencies)}]") try: with open(log_path, 'ab') as install_log: subprocess.check_call([sys.e...
class MultiProviderMenu(providers.MultiProviderHandler, Menu): def __init__(self, names, parent): providers.MultiProviderHandler.__init__(self, names, parent) Menu.__init__(self, parent) for p in self.get_providers(): self.on_provider_added(p) def on_provider_added(self, prov...
def validate_consumption(obj: dict, zone_key: ZoneKey) -> None: validate_datapoint_format(datapoint=obj, kind='consumption', zone_key=zone_key) if ((obj.get('consumption') or 0) < 0): raise ValidationError(f"{zone_key}: consumption has negative value {obj['consumption']}") if (abs((obj.get('consumpt...
_frequency(timedelta(days=1)) def fetch_production(zone_key: ZoneKey=ZoneKey('US-CAL-CISO'), session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> list: target_url = get_target_url(target_datetime, kind='production') if (target_datetime is None): ...
def upgrade(): op.execute('alter type connectiontype rename to connectiontype_old') op.execute("create type connectiontype as enum('mongodb', 'mysql', ' 'snowflake', 'redshift', 'mssql', 'mariadb', 'bigquery', 'saas', 'manual', 'manual_webhook', 'timescale', 'fides', 'sovrn', 'attentive', 'dynamodb', 'postgres'...
class Setup(object): def __init__(self, G1_side, X2): self.G1_side = G1_side self.X2 = X2 def from_file(cls, filename): contents = open(filename, 'rb').read() powers = (2 ** contents[SETUP_FILE_POWERS_POS]) values = [int.from_bytes(contents[i:(i + 32)], 'little') for i in...
class MemoryBaseStore(KeyValueStore): def __init__(self): self.values = {} def get(self, key, original_timestamp=None): tupl = self.values.get(key) if (not tupl): return None (value, created_at, expires_at) = tupl if ((original_timestamp is not None) and (crea...
class Solution(): def isMatch(self, s: str, p: str) -> bool: def match_pattern(s, p, sidx, pidx, track): if ((sidx, pidx) in track): return track[(sidx, pidx)] if ((sidx >= len(s)) and (pidx >= len(p))): return True elif (sidx >= len(s)): ...
class OptionSeriesHeatmapSonificationContexttracksMappingNoteduration(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): ...
def extractGreenappletranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, n...
def permission_manager(view, view_args, view_kwargs, *args, **kwargs): methods = 'GET,POST,DELETE,PATCH' if ('id' in kwargs): view_kwargs['id'] = kwargs['id'] if kwargs.get('methods'): methods = kwargs['methods'] if (request.method not in methods): return view(*view_args, **view_...
def read_expected_ttx(testfile, tableTag): name = os.path.splitext(testfile)[0] xml_expected_path = getpath(('%s.ttx.%s' % (name, tagToXML(tableTag)))) with open(xml_expected_path, 'r', encoding='utf-8') as xml_file: xml_expected = ttLibVersion_RE.sub('', xml_file.read()) return xml_expected
.usefixtures('use_tmpdir') def test_stop_on_fail_is_parsed_external(): with open('fail_job', 'w+', encoding='utf-8') as f: f.write('INTERNAL False\n') f.write('EXECUTABLE echo\n') f.write('MIN_ARG 1\n') f.write('STOP_ON_FAIL True\n') job_internal = WorkflowJob.from_file(name='FAI...
def crlf_check(uri, method, headers, body, scanid): if ((method == 'GET') or (method == 'DEL')): crlf_get_uri_method(uri, method, headers, scanid) crlf_get_url_method(uri, headers, scanid) if ((method == 'POST') or (method == 'PUT')): crlf_post_method(uri, method, headers, body, scanid)
def get_tvtk_name(vtk_name): if (vtk_name[:3] == 'vtk'): name = vtk_name[3:] dig2name = {'1': 'One', '2': 'Two', '3': 'Three', '4': 'Four', '5': 'Five', '6': 'Six', '7': 'Seven', '8': 'Eight', '9': 'Nine', '0': 'Zero'} if (name[0] in string.digits): return (dig2name[name[0]] + na...
class RelationshipMemberWafTag(ModelNormal): allowed_values = {} validations = {} _property def additional_properties_type(): lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(): lazy_impo...
_required(login_url='/login') def ArticleUpdate(request, article_id): if (request.method == 'GET'): category = Category_Article.objects.all() try: article = Article.objects.get(id=article_id) except Exception: return Http404 return render(request, 'pc/article_...
class SequenceResult(): def __init__(self, request_buffer, result_index: int, offset: int=0, length: int=None): self.request_buffer: OpenAIModelOutputBuffer = request_buffer self.result_index = result_index self.offset = offset self.length = length self.collected_data = [] ...
class OptionPlotoptionsVectorStatesHover(Options): def animation(self) -> 'OptionPlotoptionsVectorStatesHoverAnimation': return self._config_sub_data('animation', OptionPlotoptionsVectorStatesHoverAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): ...
class OptionSeriesErrorbarData(Options): def accessibility(self) -> 'OptionSeriesErrorbarDataAccessibility': return self._config_sub_data('accessibility', OptionSeriesErrorbarDataAccessibility) def className(self): return self._config_get(None) def className(self, text: str): self._c...
class FixMatrixOpTest(unittest.TestCase): def test_fix_matrix_addition(self) -> None: self.maxDiff = None bmg = BMGraphBuilder() zeros = bmg.add_real_matrix(torch.zeros(2)) ones = bmg.add_pos_real_matrix(torch.ones(2)) tensor_elements = [] for index in range(0, 2): ...
def parse_area(tags): if ('building' in tags): group = 'building' kind = tags['building'] if (kind == 'yes'): for key in ['amenity', 'tourism']: if (key in tags): kind = tags[key] break if (kind != 'yes'): ...
class EventFile(OutputFile): _file_suffix = '.xpe' def __init__(self, additional_suffix, directory=None, delimiter=None, clock=None, time_stamp=None): if (directory is None): directory = defaults.eventfile_directory if (additional_suffix is None): additional_suffix = '' ...
class ObjectCreationTest(BaseEvenniaTest): def test_channel_create(self): description = 'A place to talk about coffee.' (obj, errors) = DefaultChannel.create('coffeetalk', description=description) self.assertTrue(obj, errors) self.assertFalse(errors, errors) self.assertEqual(...
def test_substitute_branches_by(): asforest = AbstractSyntaxForest(condition_handler=ConditionHandler()) code_node_1 = asforest.add_code_node([Assignment(var('u'), const(9))]) code_node_2 = asforest.add_code_node([Break()]) code_node_3 = asforest.add_code_node([Assignment(var('v'), const(9))]) code_...
def _create_model(): base_models = [LogExpModel(lgbm.sklearn.LGBMRegressor()), LogExpModel(ctb.CatBoostRegressor(verbose=False))] ensemble = EnsembleModel(base_models=base_models, bagging_fraction=BAGGING_FRACTION, model_cnt=MODEL_CNT) model = GroupedOOFModel(base_model=ensemble, group_column='ticker', fold...
class OptionSeriesArearangeAccessibility(Options): def description(self): return self._config_get(None) def description(self, text: str): self._config(text, js_type=False) def descriptionFormat(self): return self._config_get(None) def descriptionFormat(self, text: str): s...
def test_structlog_processor_no_span(elasticapm_client): transaction = elasticapm_client.begin_transaction('test') event_dict = {} new_dict = structlog_processor(None, None, event_dict) assert (new_dict['transaction.id'] == transaction.id) assert (new_dict['trace.id'] == transaction.trace_parent.tra...
def test_modify_base(mockproject): code = BASE_CONTRACT.split('\n') code[4] += '// comment' code = '\n'.join(code) with mockproject._path.joinpath('contracts/BaseFoo.sol').open('w') as fp: fp.write(code) mockproject.load() assert (sorted(mockproject._compile.call_args[0][0]) == ['contrac...
def render_table(header, rows): (columns, sep) = header line = '' div = '' for (column, _, width) in columns: line += sep line += column div += sep div += ('=' * width) (yield line) (yield div) for row in rows: line = '' assert (len(row) == len...
def extractJujubbtranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name,...
class HttpImageHandler(BaseHTTPRequestHandler): def log_message(self, format, *args): log_line = (format % args) log.debug(log_line) return def do_GET(self): log.debug('HttpImageHandler:do_GET()') self.serve_image() return def do_HEAD(self): log.debug(...
def _parse_func_metadata(ops: List[Operator], inputs: List[Tensor], outputs: List[Tensor], input_accessors: List[TensorAccessor], output_accessors: List[TensorAccessor], original_inputs: List[Tensor], original_outputs: List[Tensor], backend_spec: BackendSpec) -> FusedElementwiseMetaData: (mixed_jagged_dense_indexin...
class OptionPlotoptionsGaugeSonificationDefaultinstrumentoptionsMappingFrequency(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, tex...
def observer_change_handler(event, graph, handler, target, dispatcher): if all(((event.old is not skipped) for skipped in UNOBSERVABLE_VALUES)): try: add_or_remove_notifiers(object=event.old, graph=graph, handler=handler, target=target, dispatcher=dispatcher, remove=True) except Notifier...
def change_owner_of_output_files(files_dir: Path, owner: str) -> int: if (not match('\\d+:\\d+', owner)): logging.error('ownership string should have the format <user id>:<group id>') return 1 (_, return_code_chown) = execute_shell_command_get_return_code(f'sudo chown -R {owner} {files_dir}') ...
def test_iter_sse_id_retry_invalid() -> None: class Body( def __iter__(self) -> Iterator[bytes]: (yield b'retry: 1667a\n') (yield b'\n') response = headers={'content-type': 'text/event-stream'}, stream=Body()) events = list(EventSource(response).iter_sse()) assert (len(e...
class OptionSeriesSankeySonificationTracksMappingVolume(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): self._co...
def startup(): dp_proj = '' dp_argv = {} (argv_opts, argv_left) = getopt(sys.argv[1:], 'hvtr:i:o:w:e:l:p:d:', ['help', 'version', 'temporary', 'reset=', 'input=', 'output=', 'export=', 'window=', 'sequence=', 'lang=', 'locale=', 'port=', 'project=', 'dir=']) for (opt_name, opt_value) in argv_opts: ...
def get_field_kwargs(field_name, model_field): kwargs = {} validator_kwarg = list(model_field.validators) kwargs['model_field'] = model_field if (model_field.verbose_name and needs_label(model_field, field_name)): kwargs['label'] = capfirst(model_field.verbose_name) if model_field.help_text:...
class HCI_Cmd(HCI): HCI_CMD_STR = {1025: 'COMND Inquiry', 1026: 'COMND Inquiry_Cancel', 1027: 'COMND Periodic_Inquiry_Mode', 1028: 'COMND Exit_Periodic_Inquiry_Mode', 1029: 'COMND Create_Connection', 1030: 'COMND Disconnect', 1032: 'COMND Create_Connection_Cancel', 1033: 'COMND Accept_Connection_Request', 1034: 'CO...
class Strategy(GenericStrategy): def __init__(self, **kwargs: Any) -> None: aw1_aea: Optional[str] = kwargs.pop('aw1_aea', None) if (aw1_aea is None): raise ValueError('aw1_aea must be provided!') self.aw1_aea = aw1_aea self.minimum_hours_between_txs = kwargs.pop('mininum...
def instance_details(request): last_tag_cmd = ['git', 'describe', '--tags', '--always', '--abbrev=0'] last_commit_cmd = ['git', 'log', '-1', '--pretty=oneline'] versions = {'tag': check_output(last_tag_cmd).decode('utf-8').strip(), 'commit': check_output(last_commit_cmd).decode('utf-8').strip(), 'django': g...
class TestIndicesStatsRunner(): ('elasticsearch.Elasticsearch') .asyncio async def test_indices_stats_without_parameters(self, es): es.indices.stats = mock.AsyncMock(return_value={}) indices_stats = runner.IndicesStats() result = (await indices_stats(es, params={})) assert (r...
class TestHiddenFieldUniquenessForDateValidation(TestCase): def test_repr_date_field_not_included(self): class TestSerializer(serializers.ModelSerializer): class Meta(): model = HiddenFieldUniqueForDateModel fields = ('id', 'slug') serializer = TestSeriali...
def extractOootransWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type) ...
.benchmark(group='import/export') def test_benchmark_cube_import(benchmark, testpath, tmp_path): cube1 = xtgeo.cube_from_file(join(testpath, 'cubes/reek/syntseis__seismic_depth_stack.segy')) fname = join(tmp_path, 'syntseis__seismic_depth_stack.xtgrecube') cube1.to_file(fname, fformat='xtgregcube') cube...
_main(config_path='conf', config_name='config') def main(args): logger.info(repr(args)) import os logger.info('%s %s', os.getcwd(), __file__) xp = get_xp() logger.info(xp.sig) use_cuda = ((not args.no_cuda) and torch.cuda.is_available()) torch.manual_seed(args.seed) device = torch.device...
def writeResultHDF(pOutFileName, pAcceptedData, pRejectedData, pAllResultData, pInputData, pAlpha, pTest): resultFileH5Object = h5py.File(pOutFileName, 'w') resultFileH5Object.attrs['type'] = 'differential' resultFileH5Object.attrs['version'] = __version__ resultFileH5Object.attrs['alpha'] = pAlpha ...
class COLRVariationMergerTest(): .parametrize('paints, expected_xml, expected_varIdxes', [pytest.param([{'Format': int(ot.PaintFormat.PaintSolid), 'PaletteIndex': 0, 'Alpha': 1.0}, {'Format': int(ot.PaintFormat.PaintSolid), 'PaletteIndex': 0, 'Alpha': 1.0}], ['<Paint Format="2"><!-- PaintSolid -->', ' <PaletteInde...
def main(): module_spec = schema_to_module_spec(versioned_schema) mkeyname = 'peer-name' fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_p...
def trace(mod: nn.Module, sample_inputs: Sequence[Any], remove_assertions: bool=True, remove_exceptions: bool=True, use_acc_normalization: bool=True, ast_rewriter_allow_list: Optional[Set[Type[nn.Module]]]=None, leaf_module_list: Optional[Set[Type[nn.Module]]]=None, acc_normalization_block_list: Optional[Set[Tuple[(str...
def alloc_css_item(pool: list, token_type: str, start: int, end: int): if pool: item = pool.pop() item['type'] = token_type item['region'].a = start item['region'].b = end else: item = {'type': token_type, 'region': sublime.Region(start, end)} return item
class Migration(migrations.Migration): initial = True dependencies = [] operations = [migrations.CreateModel(name='Category', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=20)), ('slug', models.SlugField()), ('...
class OptionPlotoptionsArearangeSonificationTracksMappingHighpassFrequency(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str...
def query_capacity(in_domain: str, session: Session, target_datetime: datetime) -> (str | None): params = {'documentType': 'A68', 'processType': 'A33', 'in_Domain': in_domain, 'periodStart': target_datetime.strftime('%Y'), 'periodEnd': target_datetime.strftime('%Y')} return query_ENTSOE(session, params, target_...
class OptionSeriesStreamgraphSonificationTracksMappingPlaydelay(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): ...
def split_and_zip_data_files(zip_file_path, source_path, data_file_name, file_format, download_job=None): with SubprocessTrace(name=f'job.{JOB_TYPE}.download.zip', service='bulk-download', span_type=SpanTypes.WORKER, source_path=source_path, zip_file_path=zip_file_path) as span: try: log_time = ...
def get_record(fileObj, line_no=None, offset=0): line = fileObj.readline() if ((line_no is not None) and line): line_no += 1 while line: tline = line.strip() if ((not tline) or tline.startswith(str2octs('#'))): offset += len(line) line = fileObj.readline() ...
('ciftify.config.verify_msm_available') ('ciftify.bidsapp.fmriprep_ciftify.run') def test_ux03_default_two_participants_for_ds005(mock_run, mock_vmsm): uargs = [ds005_bids, '/output/dir', 'participant', '--participant_label=01,14'] ret = simple_main_run(uargs) call_list = parse_call_list_into_strings(mock_r...
class DPMSolver(Scheduler): def __init__(self, num_inference_steps: int, num_train_timesteps: int=1000, initial_diffusion_rate: float=0.00085, final_diffusion_rate: float=0.012, noise_schedule: NoiseSchedule=NoiseSchedule.QUADRATIC, device: (Device | str)='cpu', dtype: Dtype=float32): super().__init__(num_i...
class ClientContextResponse(Response): def __init__(self, original_response: Response): super().__init__() self.status = original_response.status self.headers._data.update(original_response.headers._data) self.cookies.update(original_response.cookies.copy()) self.__dict__.upd...
class FwAnalysisStatus(): files_to_unpack: Set[str] files_to_analyze: Set[str] total_files_count: int hid: str analysis_plugins: Dict[(str, int)] start_time: float = field(default_factory=time) completed_files: Set[str] = field(default_factory=set) total_files_with_duplicates: int = 1 ...
class TestLegalDoc(unittest.TestCase): ('webservices.rest.legal.es_client.search', legal_doc_data) def test_legal_doc(self): app = rest.app.test_client() response = app.get((('/v1/legal/' + DOCS_PATH) + '/doc_type/1?api_key=1234')) assert (response.status_code == 200) result = js...
class Guild(models.Model): class Meta(): verbose_name = '' verbose_name_plural = '' id = models.AutoField(primary_key=True) name = models.CharField('', max_length=20, unique=True, help_text='') leader = models.OneToOneField(Player, models.CASCADE, unique=True, related_name='leading_guild...
_settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}) class MemoizeDecoratorTest(SimpleTestCase): def test_cached_function_with_basic_arguments(self): test_func = Mock(side_effect=(lambda *args, **kwargs: (args, kwargs)), __qualname__='test_func') cached_func = ...
def _format_date_time(date_time): tm = date_time.timetuple() offset = 0 sign = '+' if (date_time.tzinfo is not None): if (date_time.tzinfo.__class__ is not TZFixedOffset): raise ValueError('Only TZFixedOffset supported.') offset = date_time.tzinfo.offset if (offset < 0): ...
def _get_revlog_graph(cid): entries = mw.col.db.all(('select * from revlog where cid = %s and (type = 1 or type = 2)' % cid)) html = "<div class='w-100'>%s</div>" blocks = '' for (_, _, _, ease, ivl, _, _, _, type) in entries: ease = ((ease + 1) if ((type == 2) and (ease > 1)) else ease) ...
class Tensor(Node): def __init__(self, shape: List[IntVar], name: str=None, src_ops: Iterable[Node]=None, dst_ops: Iterable[Node]=None, dtype: str='float16', is_input: bool=False, is_output: bool=False, value: Any=None, is_view_of: Any=None, is_internal_constant: bool=False, skip_constant_folding: bool=False, check...
class TestWrapperGenerator(unittest.TestCase): def setUp(self): self.wg = _cache def test_find_type(self): wg = self.wg sigs = ['int', 'vtkOpenGLVolumeMapper', ('int', 'int', 'float', 'list'), ('int', 'vtkActor', 'vtkXMLReader'), ['vtkImageActor', 'vtkExporter'], ['int', 'vtkDataArray', ...
class CoverChooser(GObject.GObject): __gsignals__ = {'covers-fetched': (GObject.SignalFlags.RUN_LAST, None, (object,)), 'cover-chosen': (GObject.SignalFlags.RUN_LAST, None, (object, object))} def __init__(self, parent, track, search=None): GObject.GObject.__init__(self) self.parent = parent ...
class TestHtml5AdvancedSelectors2(util.PluginTestCase): def setup_fs(self): template = self.dedent('\n <!DOCTYPE html>\n <html>\n <head>\n <meta content="text/html; charset=UTF-8">\n </head>\n <body>\n <div class="aaaa">aaaa\n...