language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
realpython__materials
web-scraping-with-scrapy-and-mongodb/books/tests/test_book.py
{ "start": 304, "end": 2518 }
class ____(unittest.TestCase): def setUp(self): self.spider = BookSpider() self.example_html = _get_sample_html_content() self.response = HtmlResponse( url="https://books.toscrape.com", body=self.example_html, encoding="utf-8", ) def test_pars...
BookSpiderTest
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/transfers/s3_to_redshift.py
{ "start": 1504, "end": 12036 }
class ____(BaseOperator): """ Executes an COPY command to load files from s3 to Redshift. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:S3ToRedshiftOperator` :param table: reference to a specific table in redshift database...
S3ToRedshiftOperator
python
pandas-dev__pandas
pandas/tests/indexes/categorical/test_append.py
{ "start": 102, "end": 2245 }
class ____: @pytest.fixture def ci(self): categories = list("cab") return CategoricalIndex(list("aabbca"), categories=categories, ordered=False) def test_append(self, ci): # append cats with the same categories result = ci[:3].append(ci[3:]) tm.assert_index_equal(res...
TestAppend
python
jupyterlab__jupyterlab
jupyterlab/labextensions.py
{ "start": 14847, "end": 15822 }
class ____(BaseExtensionApp): description = "Disable labextension(s) by name" aliases = disable_aliases level = Unicode("sys_prefix", help="Level at which to disable: sys_prefix, user, system").tag( config=True ) def run_task(self): app_options = AppOptions( app_dir=sel...
DisableLabExtensionsApp
python
joke2k__faker
tests/providers/test_date_time.py
{ "start": 42064, "end": 42420 }
class ____(unittest.TestCase): def setUp(self): self.fake = Faker("ro_RO") Faker.seed(0) def test_day(self): day = self.fake.day_of_week() assert day in RoRoProvider.DAY_NAMES.values() def test_month(self): month = self.fake.month_name() assert month in RoRo...
TestRoRo
python
cython__cython
Cython/Shadow.py
{ "start": 16982, "end": 17865 }
class ____: """ cython.dataclasses just shadows the standard library modules of the same name """ def __init__(self, module): self.__path__ = [] self.__file__ = None self.__name__ = module self.__package__ = module def __getattr__(self, attr): # we typically ...
CythonDotImportedFromElsewhere
python
pytorch__pytorch
test/onnx/model_defs/lstm_flattening_result.py
{ "start": 69, "end": 274 }
class ____(nn.LSTM): def forward(self, input, *fargs, **fkwargs): output, (hidden, cell) = nn.LSTM.forward(self, input, *fargs, **fkwargs) return output, hidden, cell
LstmFlatteningResult
python
huggingface__transformers
src/transformers/models/ernie/modular_ernie.py
{ "start": 4818, "end": 4874 }
class ____(BertSelfAttention): pass
ErnieSelfAttention
python
kubernetes-client__python
kubernetes/client/models/v1beta2_device_claim_configuration.py
{ "start": 383, "end": 5016 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1beta2DeviceClaimConfiguration
python
huggingface__transformers
src/transformers/models/whisper/generation_whisper.py
{ "start": 9291, "end": 110261 }
class ____(GenerationMixin): def _extract_token_timestamps( self, generate_outputs, alignment_heads, time_precision=0.02, num_frames=None, num_input_ids=None ): """ Calculates token-level timestamps using the encoder-decoder cross-attentions and dynamic time-warping (DTW) to map ...
WhisperGenerationMixin
python
getsentry__sentry
tests/sentry/rules/filters/test_issue_category.py
{ "start": 1715, "end": 2324 }
class ____( RuleTestCase, SnubaTestCase, PerformanceIssueTestCase, ): rule_cls = IssueCategoryFilter def test_transaction_category(self) -> None: tx_event = self.create_performance_issue() assert tx_event.group self.assertPasses(self.get_rule(data={"value": GroupCategory.PER...
IssueCategoryFilterPerformanceTest
python
kamyu104__LeetCode-Solutions
Python/rle-iterator.py
{ "start": 29, "end": 611 }
class ____(object): def __init__(self, A): """ :type A: List[int] """ self.__A = A self.__i = 0 self.__cnt = 0 def next(self, n): """ :type n: int :rtype: int """ while self.__i < len(self.__A): if n > self.__...
RLEIterator
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 187467, "end": 188572 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "repository_id", "name", "description", "template", "homepage_url", "has_wiki_enabled", "has_issues_enabled", "has_pr...
UpdateRepositoryInput
python
PyCQA__pylint
tests/functional/p/postponed/postponed_evaluation_pep585.py
{ "start": 1128, "end": 1186 }
class ____(TypedDict): my_var: list[int]
CustomTypedDict3
python
walkccc__LeetCode
solutions/344. Reverse String/344.py
{ "start": 0, "end": 168 }
class ____: def reverseString(self, s: list[str]) -> None: l = 0 r = len(s) - 1 while l < r: s[l], s[r] = s[r], s[l] l += 1 r -= 1
Solution
python
tiangolo__fastapi
tests/test_dependency_yield_scope.py
{ "start": 781, "end": 6873 }
class ____: def __init__(self, name: str = "default") -> None: self.name = name self.open = True def get_named_session(session: SessionRequestDep, session_b: SessionDefaultDep) -> Any: assert session is session_b named_session = NamedSession(name="named") yield named_session, session_b...
NamedSession
python
numba__llvmlite
llvmlite/binding/newpassmanagers.py
{ "start": 1647, "end": 3302 }
class ____(Structure): _fields_ = [ ('basicblock', c_size_t), ('diamond', c_size_t), ('fanout', c_size_t), ('fanout_raise', c_size_t)] def dump_refprune_stats(printout=False): """ Returns a namedtuple containing the current values for the refop pruning statistics. If kwarg ...
_c_PruneStats
python
jina-ai__jina
tests/unit/orchestrate/flow/flow-construct/test_flow.py
{ "start": 7698, "end": 8060 }
class ____(BaseExecutor): """Class used in Flow YAML""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # pod/pod-specific assert os.environ['key1'] == 'value1' assert os.environ['key2'] == 'value2' # inherit from parent process assert os.e...
EnvChecker1
python
dagster-io__dagster
python_modules/libraries/dagster-databricks/dagster_databricks/pipes.py
{ "start": 23171, "end": 30860 }
class ____(BasePipesDatabricksClient, TreatAsResourceParam): """Pipes client for Databricks Serverless. Args: client (WorkspaceClient): A databricks `WorkspaceClient` object. volume_path (str): Path to the volume that will be used by this client to read and write temporary files. contex...
PipesDatabricksServerlessClient
python
huggingface__transformers
src/transformers/models/squeezebert/modeling_squeezebert.py
{ "start": 15836, "end": 19122 }
class ____(SqueezeBertPreTrainedModel): def __init__(self, config): super().__init__(config) self.embeddings = SqueezeBertEmbeddings(config) self.encoder = SqueezeBertEncoder(config) self.pooler = SqueezeBertPooler(config) # Initialize weights and apply final processing ...
SqueezeBertModel
python
walkccc__LeetCode
solutions/1246. Palindrome Removal/1246.py
{ "start": 0, "end": 717 }
class ____: def minimumMoves(self, arr: list[int]) -> int: n = len(arr) # dp[i][j] := the minimum number of moves to remove all numbers from arr[i..j] dp = [[n] * n for _ in range(n)] for i in range(n): dp[i][i] = 1 for i in range(n - 1): dp[i][i + 1] = 1 if arr[i] == arr[i + 1] else...
Solution
python
streamlit__streamlit
lib/streamlit/watcher/event_based_path_watcher.py
{ "start": 2541, "end": 4452 }
class ____: """Watches a single path on disk using watchdog.""" @staticmethod def close_all() -> None: """Close the _MultiPathWatcher singleton.""" path_watcher = _MultiPathWatcher.get_singleton() path_watcher.close() _LOGGER.debug("Watcher closed") def __init__( ...
EventBasedPathWatcher
python
ray-project__ray
python/ray/data/tests/test_webdataset.py
{ "start": 217, "end": 9067 }
class ____: def __init__(self, path): self.path = path self.tar = tarfile.open(path, "w") def __enter__(self): return self def __exit__(self, *args): self.tar.close() def write(self, name, data): f = self.tar.tarinfo() f.name = name f.size = len...
TarWriter
python
django__django
tests/model_forms/tests.py
{ "start": 32019, "end": 32351 }
class ____(forms.ModelForm): """ A form that replaces the model's url field with a custom one. This should prevent the model field's validation from being called. """ url = forms.CharField(required=False) class Meta: fields = ("name", "slug") model = Category
IncompleteCategoryFormWithFields
python
openai__openai-python
src/openai/resources/beta/chatkit/threads.py
{ "start": 18502, "end": 19067 }
class ____: def __init__(self, threads: AsyncThreads) -> None: self._threads = threads self.retrieve = _legacy_response.async_to_raw_response_wrapper( threads.retrieve, ) self.list = _legacy_response.async_to_raw_response_wrapper( threads.list, ) ...
AsyncThreadsWithRawResponse
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_health/asset_materialization_health.py
{ "start": 14489, "end": 14678 }
class ____: num_failed_partitions: int num_missing_partitions: int total_num_partitions: int @whitelist_for_serdes @record.record
AssetHealthMaterializationDegradedPartitionedMeta
python
pyca__cryptography
src/cryptography/hazmat/primitives/serialization/ssh.py
{ "start": 6758, "end": 8404 }
class ____: """Build recursive structure without data copy.""" flist: list[utils.Buffer] def __init__(self, init: list[utils.Buffer] | None = None) -> None: self.flist = [] if init: self.flist.extend(init) def put_raw(self, val: utils.Buffer) -> None: """Add plain ...
_FragList
python
weaviate__weaviate-python-client
weaviate/collections/classes/generative.py
{ "start": 7290, "end": 7772 }
class ____(_GenerativeConfigRuntime): generative: Union[GenerativeSearches, _EnumLikeStr] = Field( default=GenerativeSearches.DUMMY, frozen=True, exclude=True ) def _to_grpc(self, opts: _GenerativeConfigRuntimeOptions) -> generative_pb2.GenerativeProvider: self._validate_multi_modal(opts) ...
_GenerativeDummy
python
aio-libs__aiohttp
aiohttp/streams.py
{ "start": 506, "end": 994 }
class ____(Generic[_T]): __slots__ = ("read_func",) def __init__(self, read_func: Callable[[], Awaitable[_T]]) -> None: self.read_func = read_func def __aiter__(self) -> "AsyncStreamIterator[_T]": return self async def __anext__(self) -> _T: try: rv = await self.r...
AsyncStreamIterator
python
django__django
django/db/utils.py
{ "start": 3986, "end": 6515 }
class ____(BaseConnectionHandler): settings_name = "DATABASES" # Connections needs to still be an actual thread local, as it's truly # thread-critical. Database backends should use @async_unsafe to protect # their code from async contexts, but this will give those contexts # separate connections in ...
ConnectionHandler
python
PrefectHQ__prefect
tests/results/test_result_record.py
{ "start": 315, "end": 2349 }
class ____: def test_deserialize_with_full_data(self): record = ResultRecord( result="The results are in...", metadata=ResultRecordMetadata( storage_key="my-storage-key", serializer=JSONSerializer() ), ) serialized = record.serialize() ...
TestResultRecord
python
run-llama__llama_index
llama-index-experimental/llama_index/experimental/retrievers/natural_language/nl_csv_retriever.py
{ "start": 409, "end": 1092 }
class ____(NLDataframeRetriever): def __init__( self, csv_path: str, llm: llm, name: Optional[str] = None, text_to_sql_prompt: Optional[BasePromptTemplate] = None, similarity_top_k: int = DEFAULT_SIMILARITY_TOP_K, callback_manager: Optional[CallbackManager] = ...
NLCSVRetriever
python
pytorch__pytorch
test/dynamo/test_export.py
{ "start": 154074, "end": 156906 }
class ____(torch._dynamo.test_case.TestCase): def test_export_with_parameters(self, device): class MyModule(torch.nn.Module): def __init__(self) -> None: super().__init__() self.features = torch.nn.Sequential( torch.nn.Conv2d( ...
ExportTestsDevice
python
huggingface__transformers
src/transformers/models/esm/modeling_esm.py
{ "start": 15664, "end": 16646 }
class ____(nn.Module): def __init__(self, config, layer_idx=None, is_cross_attention=False): super().__init__() self.self = EsmSelfAttention(config, layer_idx=layer_idx, is_cross_attention=is_cross_attention) self.output = EsmSelfOutput(config) self.LayerNorm = nn.LayerNorm(config.h...
EsmAttention
python
google__jax
jax/experimental/mosaic/gpu/utils.py
{ "start": 17162, "end": 31306 }
class ____: base: ir.Value | int length: int def __post_init__(self): if isinstance(self.base, int) and self.base < 0: raise ValueError(f"base must be non-negative, got {self.base}") if self.length < 0: raise ValueError(f"length must be non-negative, got {self.length}") ds = DynamicSlice ...
DynamicSlice
python
apache__airflow
airflow-core/src/airflow/exceptions.py
{ "start": 2864, "end": 3017 }
class ____(AirflowException): """Raise by providers when imports are missing for optional provider features."""
AirflowOptionalProviderFeatureException
python
allegroai__clearml
clearml/backend_api/services/v2_20/models.py
{ "start": 65844, "end": 84900 }
class ____(Request): """ Get all models :param name: Get only models whose name matches this pattern (python regular expression syntax) :type name: str :param user: List of user IDs used to filter results by the model's creating user :type user: Sequence[str] :param ready: I...
GetAllRequest
python
pytest-dev__pytest
testing/test_config.py
{ "start": 46722, "end": 63080 }
class ____: def test_basic_behavior(self, _sys_snapshot) -> None: option_dict = {"verbose": 444, "foo": "bar", "capture": "no"} args = ["a", "b"] config = Config.fromdictargs(option_dict, args) with pytest.raises(AssertionError): config.parse(["should refuse to parse aga...
TestConfigFromdictargs
python
PyCQA__pylint
tests/functional/s/string/string_formatting.py
{ "start": 245, "end": 341 }
class ____: """ Has a __getattr__ """ def __getattr__(self, _): return self
Custom
python
facebook__pyre-check
client/commands/infer.py
{ "start": 15671, "end": 15769 }
class ____(FieldAnnotation): parent: str @dataclasses.dataclass(frozen=True)
AttributeAnnotation
python
tiangolo__fastapi
tests/test_compat_params_v1.py
{ "start": 509, "end": 42328 }
class ____(BaseModel): name: str price: float description: Optional[str] = None app = FastAPI() @app.get("/items/{item_id}") def get_item_with_path( item_id: Annotated[int, Path(title="The ID of the item", ge=1, le=1000)], ): return {"item_id": item_id} @app.get("/items/") def get_items_with_q...
Item
python
sphinx-doc__sphinx
sphinx/util/docutils.py
{ "start": 24315, "end": 30759 }
class ____(nodes.NodeVisitor): """A base class for Sphinx translators. This class adds a support for visitor/departure method for super node class if visitor/departure method for node class is not found. It also provides helper methods for Sphinx translators. .. versionadded:: 2.0 .. note:: ...
SphinxTranslator
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 17245, "end": 18101 }
class ____(sgqlc.types.Enum): """The possible values for the enterprise base repository permission setting. Enumeration Choices: * `ADMIN`: Organization members will be able to clone, pull, push, and add new collaborators to all organization repositories. * `NONE`: Organization members will ...
EnterpriseDefaultRepositoryPermissionSettingValue
python
pytorch__pytorch
test/test_dataloader.py
{ "start": 35437, "end": 35713 }
class ____(Dataset): def __init__(self, length): self.length = length def __getitem__(self, indices): assert isinstance(indices, (list, tuple)) return torch.as_tensor(indices) def __len__(self): return self.length
BulkLoadingDataset
python
python-openxml__python-docx
src/docx/opc/constants.py
{ "start": 8549, "end": 9087 }
class ____: """Constant values for OPC XML namespaces.""" DML_WORDPROCESSING_DRAWING = ( "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" ) OFC_RELATIONSHIPS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships" OPC_RELATIONSHIPS = "http://schemas.o...
NAMESPACE
python
django__django
tests/auth_tests/test_mixins.py
{ "start": 618, "end": 726 }
class ____(View): def get(self, request, *args, **kwargs): return HttpResponse()
EmptyResponseView
python
scipy__scipy
scipy/integrate/_ivp/bdf.py
{ "start": 1944, "end": 16821 }
class ____(OdeSolver): """Implicit method based on backward-differentiation formulas. This is a variable order method with the order varying automatically from 1 to 5. The general framework of the BDF algorithm is described in [1]_. This class implements a quasi-constant step size as explained in [2]_....
BDF
python
pytorch__pytorch
torch/_dynamo/create_parameter_op.py
{ "start": 840, "end": 2561 }
class ____(torch.autograd.Function): @staticmethod # pyrefly: ignore [bad-override] def forward(ctx: Any, tensor: Any, placeholder: Any) -> torch.nn.Parameter: assert not tensor.requires_grad return placeholder.set_(tensor) @staticmethod def backward(ctx: Any, *grad_outputs: torch.T...
TracableCreateParameter
python
huggingface__transformers
tests/models/esm/test_modeling_esm.py
{ "start": 13225, "end": 15295 }
class ____(TestCasePlus): def test_inference_masked_lm(self): with torch.no_grad(): model = EsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D") model.eval() input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]]) output = model(input_ids)[0] vocab_...
EsmModelIntegrationTest
python
joke2k__faker
tests/providers/test_bank.py
{ "start": 6767, "end": 7434 }
class ____: """Test ru_RU bank provider""" def test_bic(self, faker, num_samples): for _ in range(num_samples): assert re.match(r"04\d{7,9}", faker.bic()) def test_correspondent_account(self, faker, num_samples): for _ in range(num_samples): assert re.match(r"301\d{...
TestRuRu
python
getsentry__sentry
src/sentry/api/endpoints/builtin_symbol_sources.py
{ "start": 548, "end": 1028 }
class ____(Endpoint): owner = ApiOwner.OWNERS_INGEST publish_status = { "GET": ApiPublishStatus.PRIVATE, } permission_classes = () def get(self, request: Request, **kwargs) -> Response: sources = [ normalize_symbol_source(key, source) for key, source in setti...
BuiltinSymbolSourcesEndpoint
python
ApeWorX__ape
tests/functional/conftest.py
{ "start": 6057, "end": 11658 }
class ____(ContractLogicError): pass @pytest.hookimpl(trylast=True, hookwrapper=True) def pytest_collection_finish(session): with ape.networks.parse_network_choice("::test"): # Sets the active provider yield @pytest.fixture def mock_web3(mocker): return mocker.MagicMock() @pytest.fixtu...
_ContractLogicError
python
django__django
django/db/models/fields/__init__.py
{ "start": 96574, "end": 98059 }
class ____: db_returning = True def __init__(self, *args, **kwargs): kwargs["blank"] = True super().__init__(*args, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_primary_key(), ] def _check_primary_key(self...
AutoFieldMixin
python
ansible__ansible
lib/ansible/modules/hostname.py
{ "start": 20594, "end": 22222 }
class ____(object): """ This is a generic Hostname manipulation class that is subclassed based on platform. A subclass may wish to set different strategy instance to self.strategy. All subclasses MUST define platform and distribution (which may be None). """ platform = 'Generic' distr...
Hostname
python
getsentry__sentry
src/sentry/search/events/builder/profiles.py
{ "start": 1163, "end": 1279 }
class ____(ProfilesQueryBuilderMixin, BaseQueryBuilder): config_class = ProfilesDatasetConfig
ProfilesQueryBuilder
python
pandas-dev__pandas
pandas/tests/extension/base/accumulate.py
{ "start": 66, "end": 1501 }
class ____: """ Accumulation specific tests. Generally these only make sense for numeric/boolean operations. """ def _supports_accumulation(self, ser: pd.Series, op_name: str) -> bool: # Do we expect this accumulation to be supported for this dtype? # We default to assuming "no"; su...
BaseAccumulateTests
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/property17.py
{ "start": 602, "end": 696 }
class ____(RootMixin[T]): root: Model[T] def func1(s: Root[str]): x: Proto[str] = s
Root
python
tensorflow__tensorflow
tensorflow/compiler/tests/qr_op_test.py
{ "start": 1395, "end": 5745 }
class ____(xla_test.XLATestCase, parameterized.TestCase): def AdjustedNorm(self, x): """Computes the norm of matrices in 'x', adjusted for dimension and type.""" norm = np.linalg.norm(x, axis=(-2, -1)) return norm / (max(x.shape[-2:]) * np.finfo(x.dtype).eps) def CompareOrthogonal(self, x, y, rank): ...
QrOpTest
python
getsentry__sentry
src/sentry/notifications/platform/types.py
{ "start": 913, "end": 1199 }
class ____(StrEnum): """ The unique keys for each registered notification provider. """ EMAIL = ExternalProviderEnum.EMAIL SLACK = ExternalProviderEnum.SLACK MSTEAMS = ExternalProviderEnum.MSTEAMS DISCORD = ExternalProviderEnum.DISCORD
NotificationProviderKey
python
Netflix__metaflow
metaflow/tracing/propagator.py
{ "start": 941, "end": 2502 }
class ____(TextMapPropagator): def __init__(self, formatter): if formatter is None: self.formatter = TraceContextTextMapPropagator() else: self.formatter = formatter # delegating to extract function implementation of the formatter def extract( self, c...
EnvPropagator
python
huggingface__transformers
src/transformers/models/convnext/modeling_convnext.py
{ "start": 9574, "end": 10220 }
class ____(PreTrainedModel): config: ConvNextConfig base_model_prefix = "convnext" main_input_name = "pixel_values" input_modalities = ("image",) _no_split_modules = ["ConvNextLayer"] _can_record_outputs = {} # hidden states are collected explicitly @torch.no_grad() def _init_weights(s...
ConvNextPreTrainedModel
python
mlflow__mlflow
mlflow/gateway/providers/bedrock.py
{ "start": 4810, "end": 5537 }
class ____(Enum): AMAZON = "amazon" COHERE = "cohere" AI21 = "ai21" ANTHROPIC = "anthropic" @property def adapter_class(self) -> type[ProviderAdapter]: return AWS_MODEL_PROVIDER_TO_ADAPTER.get(self) @classmethod def of_str(cls, name: str): name = name.lower() f...
AmazonBedrockModelProvider
python
dagster-io__dagster
docs/sphinx/_ext/sphinx-click/tests/test_formatter.py
{ "start": 14857, "end": 17029 }
class ____(unittest.TestCase): """Validate basic ``click.Group`` instances.""" maxDiff = None def test_no_parameters(self): """Validate a `click.Group` with no parameters. This exercises the code paths for a group with *no* arguments, *no* options and *no* environment variables. ...
GroupTestCase
python
getsentry__sentry
src/sentry/seer/sentry_data_models.py
{ "start": 908, "end": 1061 }
class ____(BaseModel): trace_id: str project_id: int transaction_name: str total_spans: int spans: list[EvidenceSpan]
EvidenceTraceData
python
jina-ai__jina
jina/enums.py
{ "start": 7422, "end": 7930 }
class ____(BetterEnum): """Provider type.""" NONE = 0 #: no provider SAGEMAKER = 1 #: AWS SageMaker AZURE = 2 #: AZURE def replace_enum_to_str(obj): """ Transform BetterEnum type into string. :param obj: Target obj. :return: Transformed obj with string type values. """ for ...
ProviderType
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_unicode_ddl.py
{ "start": 600, "end": 6109 }
class ____(fixtures.TablesTest): __requires__ = ("unicode_ddl",) __backend__ = True @classmethod def define_tables(cls, metadata): global t1, t2, t3 t1 = Table( "unitable1", metadata, Column("méil", Integer, primary_key=True), Column("\u6...
UnicodeSchemaTest
python
allegroai__clearml
clearml/backend_api/services/v2_13/models.py
{ "start": 36275, "end": 37806 }
class ____(Response): """ Response of models.create endpoint. :param id: ID of the model :type id: str :param created: Was the model created :type created: bool """ _service = "models" _action = "create" _version = "2.13" _schema = { "definitions": {}, "prop...
CreateResponse
python
django__django
tests/auth_tests/test_signals.py
{ "start": 396, "end": 4892 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.u1 = User.objects.create_user(username="testclient", password="password") cls.u3 = User.objects.create_user(username="staff", password="password") def listener_login(self, user, **kwargs): self.logged_in.append(user) ...
SignalTestCase
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclassPostInit1.py
{ "start": 199, "end": 363 }
class ____: a: InitVar[int] b: InitVar[str] c: InitVar[bool] def __post_init__(self, x: float, y: str, z: int, xx: int = 3) -> None: ... @dataclass
A
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/config_types.py
{ "start": 13710, "end": 15425 }
class ____(graphene.ObjectType): fields = non_null_list(GrapheneConfigTypeField) class Meta: interfaces = (GrapheneConfigType,) name = "CompositeConfigType" def __init__( self, get_config_type: Callable[[str], ConfigTypeSnap], config_type_snap: ConfigTypeSnap, )...
GrapheneCompositeConfigType
python
jazzband__prettytable
tests/test_prettytable.py
{ "start": 45562, "end": 47219 }
class ____: row = [ "bluedevil breeze breeze-gtk eos-bash-shared glib2 " "kactivitymanagerd kde-cli-tools kde-gtk-config kdecoration" ] EXPECTED_TRUE = """+------------------------------------------+ | Field 1 | +------------------------------------------+ | ...
TestBreakOnHyphens
python
great-expectations__great_expectations
great_expectations/metrics/metric.py
{ "start": 1316, "end": 1487 }
class ____(ValueError): def __init__(self, param_name) -> None: super().__init__("{param_name} must be a non-empty string.") @dataclass_transform()
EmptyStrError
python
astropy__astropy
astropy/samp/__init__.py
{ "start": 619, "end": 1039 }
class ____(_config.ConfigNamespace): """ Configuration parameters for `astropy.samp`. """ use_internet = _config.ConfigItem( True, "Whether to allow `astropy.samp` to use the internet, if available.", aliases=["astropy.samp.utils.use_internet"], ) n_retries = _config.Co...
Conf
python
gevent__gevent
src/greentest/3.13/test_socket.py
{ "start": 144166, "end": 160361 }
class ____(SendrecvmsgServerTimeoutBase): # Tests for file descriptor passing on Unix-domain sockets. # Invalid file descriptor value that's unlikely to evaluate to a # real FD even if one of its bytes is replaced with a different # value (which shouldn't actually happen). badfd = -0x5555 def ...
SCMRightsTest
python
PyCQA__pylint
tests/functional/m/membership_protocol.py
{ "start": 1833, "end": 2148 }
class ____: valid_values = None def validate(self, value): if self.valid_values is None: return True else: # error should not be emitted here return value in self.valid_values # class is not named as abstract # but still is deduceably abstract
AbstractThing
python
allegroai__clearml
clearml/storage/helper.py
{ "start": 17527, "end": 34971 }
class ____(_Driver): """Boto3 storage adapter (simple, enough for now)""" _min_pool_connections = 512 _max_multipart_concurrency = deferred_config("aws.boto3.max_multipart_concurrency", 16) _multipart_threshold = deferred_config("aws.boto3.multipart_threshold", (1024**2) * 8) # 8 MB _multipart_chu...
_Boto3Driver
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/repeat_test.py
{ "start": 6656, "end": 9285 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate( combinations.times(test_base.default_test_combinations(), combinations.combine(index=[-1, 6, 7]))) def testInvalidIndex(self, index): dataset = dataset_ops.Dataset.from_tensor_slices([1, 2, 3])...
RepeatRandomAccessTest
python
google__pytype
pytype/types/functions.py
{ "start": 2096, "end": 2247 }
class ____: """A single function argument. Used in the matcher and for error handling.""" name: str value: base.Variable typ: base.BaseValue
Arg
python
getsentry__sentry
src/sentry/preprod/migrations/0002_drop_sentry_jsonfield.py
{ "start": 239, "end": 1535 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # o...
Migration
python
pyca__cryptography
tests/hazmat/primitives/test_argon2.py
{ "start": 1341, "end": 10924 }
class ____: @pytest.fixture(scope="class", params=variants) def clazz(self, request) -> type: return request.param @pytest.mark.parametrize( "params", vectors, ids=lambda x: f"{x[0].__name__}-params" ) def test_derive(self, params, backend): argon_clazz, params = params ...
TestArgon2
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_lookup.py
{ "start": 13943, "end": 16538 }
class ____: def __init__(self, arg: int): pass @given(st.from_type(UnknownAnnotatedType)) def test_builds_for_unknown_annotated_type(ex): assert isinstance(ex, UnknownAnnotatedType) def unknown_annotated_func(a: UnknownType, b=2, *, c: UnknownType, d=4): pass def test_raises_for_arg_with_unres...
UnknownAnnotatedType
python
django__django
tests/auth_tests/test_middleware.py
{ "start": 461, "end": 3207 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.user = User.objects.create_user( "test_user", "test@example.com", "test_password" ) cls.user2 = User.objects.create_user( "test_user2", "test2@example.com", "test_password2" ) def setUp(se...
TestAuthenticationMiddleware
python
PyCQA__pylint
tests/functional/i/invalid/invalid_name/invalid_name_property.py
{ "start": 573, "end": 775 }
class ____: """Test property setter for pattern set in attr-rgx.""" @property def foo(self): # [invalid-name] pass @foo.setter def FOOSETTER(self): pass
AnotherFooClass
python
doocs__leetcode
solution/1000-1099/1039.Minimum Score Triangulation of Polygon/Solution2.py
{ "start": 0, "end": 412 }
class ____: def minScoreTriangulation(self, values: List[int]) -> int: n = len(values) f = [[0] * n for _ in range(n)] for i in range(n - 3, -1, -1): for j in range(i + 2, n): f[i][j] = min( f[i][k] + f[k][j] + values[i] * values[k] * values[j]...
Solution
python
kamyu104__LeetCode-Solutions
Python/groups-of-special-equivalent-strings.py
{ "start": 33, "end": 411 }
class ____(object): def numSpecialEquivGroups(self, A): """ :type A: List[str] :rtype: int """ def count(word): result = [0]*52 for i, letter in enumerate(word): result[ord(letter)-ord('a') + 26*(i%2)] += 1 return tuple(resu...
Solution
python
patrick-kidger__equinox
equinox/internal/_closure_to_pytree.py
{ "start": 2020, "end": 3980 }
class ____(Module): fn: _FunctionWithEquality contents: tuple[Any, ...] | None def __init__(self, fn: types.FunctionType): self.fn = _FunctionWithEquality(fn) if fn.__closure__ is None: contents = None else: contents = tuple( closure_to_pytree...
_Closure
python
vyperlang__vyper
vyper/venom/passes/concretize_mem_loc.py
{ "start": 3819, "end": 9730 }
class ____: function: IRFunction cfg: CFGAnalysis mem_allocator: MemoryAllocator liveat: dict[IRInstruction, OrderedSet[IRAbstractMemLoc]] livesets: dict[IRAbstractMemLoc, OrderedSet[IRInstruction]] used: dict[IRInstruction, OrderedSet[IRAbstractMemLoc]] def __init__( self, ...
MemLiveness
python
huggingface__transformers
src/transformers/models/nllb_moe/modeling_nllb_moe.py
{ "start": 19478, "end": 24110 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__( self, embed_dim: int, num_heads: int, dropout: Optional[float] = 0.0, is_decoder: Optional[bool] = False, bias: Optional[bool] = True, is_causal: Opti...
NllbMoeAttention
python
langchain-ai__langchain
libs/core/langchain_core/runnables/utils.py
{ "start": 19307, "end": 22188 }
class ____: def __init__( self, *, include_names: Sequence[str] | None = None, include_types: Sequence[str] | None = None, include_tags: Sequence[str] | None = None, exclude_names: Sequence[str] | None = None, exclude_types: Sequence[str] | None = None, ...
_RootEventFilter
python
numba__numba
numba/cuda/tests/cudapy/cache_usecases.py
{ "start": 5036, "end": 5834 }
class ____(CUDATestCase): """ Tests for functionality of this module's functions. Note this does not define any "test_*" method, instead check_module() should be called by hand. """ def check_module(self, mod): self.assertPreciseEqual(mod.add_usecase(2, 3), 6) self.assertPrecise...
_TestModule
python
scipy__scipy
scipy/optimize/_nonlin.py
{ "start": 18449, "end": 19328 }
class ____(Jacobian): # generic type compatibility with scipy-stubs __class_getitem__ = classmethod(GenericAlias) def setup(self, x0, f0, func): Jacobian.setup(self, x0, f0, func) self.last_f = f0 self.last_x = x0 if hasattr(self, 'alpha') and self.alpha is None: ...
GenericBroyden
python
tornadoweb__tornado
tornado/test/locale_test.py
{ "start": 179, "end": 3040 }
class ____(unittest.TestCase): # TODO: less hacky way to get isolated tests SAVE_VARS = ["_translations", "_supported_locales", "_use_gettext"] def clear_locale_cache(self): tornado.locale.Locale._cache = {} def setUp(self): self.saved = {} # type: dict for var in TranslationL...
TranslationLoaderTest
python
realpython__materials
instance-class-static-methods/pizza.py
{ "start": 0, "end": 856 }
class ____: def __init__(self, toppings): self.toppings = list(toppings) def __repr__(self): return f"Pizza({self.toppings})" def add_topping(self, topping): self.toppings.append(topping) def remove_topping(self, topping): if topping in self.toppings: self....
Pizza
python
pypa__setuptools
pkg_resources/__init__.py
{ "start": 116865, "end": 116990 }
class ____(packaging.requirements.InvalidRequirement): "Compatibility wrapper for InvalidRequirement"
RequirementParseError
python
weaviate__weaviate-python-client
weaviate/collections/classes/aggregate.py
{ "start": 1627, "end": 2043 }
class ____: """The aggregation result for a date property.""" count: Optional[int] maximum: Optional[str] median: Optional[str] minimum: Optional[str] mode: Optional[str] AggregateResult = Union[ AggregateInteger, AggregateNumber, AggregateText, AggregateBoolean, Aggregate...
AggregateDate
python
getsentry__sentry
src/sentry/sentry_metrics/consumers/last_seen_updater.py
{ "start": 1078, "end": 1397 }
class ____: """ A filter over messages coming from a stream. Can be used to pre filter messages during consumption but potentially for other use cases as well. """ @abstractmethod def should_drop(self, message: Message[KafkaPayload]) -> bool: raise NotImplementedError
StreamMessageFilter
python
scrapy__scrapy
scrapy/pipelines/files.py
{ "start": 9355, "end": 12131 }
class ____: GCS_PROJECT_ID = None CACHE_CONTROL = "max-age=172800" # The bucket's default object ACL will be applied to the object. # Overridden from settings.FILES_STORE_GCS_ACL in FilesPipeline.from_crawler(). POLICY = None def __init__(self, uri: str): from google.cloud import stor...
GCSFilesStore
python
realpython__materials
asterioids-pygame-project/source_code_step_7/space_rocks/models.py
{ "start": 800, "end": 1947 }
class ____(GameObject): MANEUVERABILITY = 3 ACCELERATION = 0.25 BULLET_SPEED = 3 def __init__(self, position, create_bullet_callback): self.create_bullet_callback = create_bullet_callback # Make a copy of the original UP vector self.direction = Vector2(UP) super().__ini...
Spaceship
python
pypa__packaging
tests/test_requirements.py
{ "start": 17598, "end": 20800 }
class ____: def test_types_with_nothing(self) -> None: # GIVEN to_parse = "foobar" # WHEN req = Requirement(to_parse) # THEN assert isinstance(req.name, str) assert isinstance(req.extras, set) assert req.url is None assert isinstance(req.spec...
TestRequirementBehaviour
python
encode__django-rest-framework
rest_framework/generics.py
{ "start": 8025, "end": 8447 }
class ____(mixins.ListModelMixin, mixins.CreateModelMixin, GenericAPIView): """ Concrete view for listing a queryset or creating a model instance. """ def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post...
ListCreateAPIView