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
wandb__wandb
wandb/sync/sync.py
{ "start": 657, "end": 1036 }
class ____: def __init__(self, path, synced=None): self.path = path self.synced = synced self.offline = os.path.basename(path).startswith("offline-") self.datetime = datetime.datetime.strptime( os.path.basename(path).split("run-")[1].split("-")[0], "%Y%m%d_%H%M%S" ...
_LocalRun
python
getsentry__sentry
tests/sentry/features/test_flagpole_context.py
{ "start": 758, "end": 1517 }
class ____(TestCase): def test_sentry_flagpole_context_builder(self) -> None: org = self.create_organization() project = self.create_project(organization=org, platform="php") sentry_flagpole_builder = get_sentry_flagpole_context_builder() sentry_context = sentry_flagpole_builder.bui...
TestSentryFlagpoleContext
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_bitstring.py
{ "start": 424, "end": 5891 }
class ____(fixtures.TestBase): @testing.combinations( lambda: BitString("111") == BitString("111"), lambda: BitString("111") == "111", lambda: BitString("111") != BitString("110"), lambda: BitString("111") != "110", lambda: hash(BitString("011")) == hash(BitString("011")), ...
BitStringTests
python
huggingface__transformers
examples/pytorch/speech-recognition/run_speech_recognition_seq2seq.py
{ "start": 9022, "end": 25574 }
class ____: """ Data collator that will dynamically pad the inputs received. Args: processor ([`WhisperProcessor`]) The processor used for processing the data. decoder_start_token_id (`int`) The begin-of-sentence of the decoder. forward_attention_mask (`bool`)...
DataCollatorSpeechSeq2SeqWithPadding
python
spack__spack
lib/spack/spack/version/version_types.py
{ "start": 7750, "end": 17477 }
class ____(ConcreteVersion): """Class to represent versions""" __slots__ = ["version", "_string", "separators"] _string: str version: VersionTuple separators: Tuple[str, ...] def __init__(self, string: str, version: VersionTuple, separators: Tuple[str, ...]): """Create a StandardVersi...
StandardVersion
python
pytorch__pytorch
test/dynamo/test_skip_guard_eval_unsafe.py
{ "start": 153, "end": 3884 }
class ____(torch._dynamo.test_case.TestCase): def test_bool_recompile(self): def fn(x, y, c): if c: return x * y else: return x + y opt_fn = torch.compile(fn, backend="inductor") x = 2 * torch.ones(4) y = 3 * torch.ones(4) ...
RunDiffGuardTests
python
ray-project__ray
python/ray/data/_internal/logical/interfaces/logical_plan.py
{ "start": 175, "end": 936 }
class ____(Plan): """The plan with a DAG of logical operators.""" def __init__(self, dag: LogicalOperator, context: "DataContext"): super().__init__(context) self._dag = dag @property def dag(self) -> LogicalOperator: """Get the DAG of logical operators.""" return self....
LogicalPlan
python
PyCQA__bandit
tests/unit/formatters/test_xml.py
{ "start": 320, "end": 2785 }
class ____(testtools.TestCase): def setUp(self): super().setUp() conf = config.BanditConfig() self.manager = manager.BanditManager(conf, "file") (tmp_fd, self.tmp_fname) = tempfile.mkstemp() self.context = { "filename": self.tmp_fname, "lineno": 4, ...
XmlFormatterTests
python
apache__airflow
providers/microsoft/azure/tests/unit/microsoft/azure/secrets/test_key_vault.py
{ "start": 1068, "end": 6662 }
class ____: @mock.patch(f"{KEY_VAULT_MODULE}.AzureKeyVaultBackend.get_conn_value") def test_get_connection(self, mock_get_value): mock_get_value.return_value = "scheme://user:pass@host:100" conn = AzureKeyVaultBackend().get_connection("fake_conn") assert conn.host == "host" @mock.pa...
TestAzureKeyVaultBackend
python
run-llama__llama_index
llama-index-packs/llama-index-packs-node-parser-semantic-chunking/llama_index/packs/node_parser_semantic_chunking/base.py
{ "start": 4506, "end": 7145 }
class ____(MetadataAwareTextSplitter): """ Semantic splitter. Inspired by Greg's semantic chunking. """ buffer_size: int = Field( default=1, description="Number of sentences to include in each chunk." ) embed_model: Optional[BaseEmbedding] = Field( default=None, descriptio...
SemanticChunker
python
PrefectHQ__prefect
src/prefect/client/schemas/filters.py
{ "start": 36069, "end": 36579 }
class ____(PrefectBaseModel, OperatorMixin): """Filter variables. Only variables matching all criteria will be returned""" id: Optional[VariableFilterId] = Field( default=None, description="Filter criteria for `Variable.id`" ) name: Optional[VariableFilterName] = Field( default=None, de...
VariableFilter
python
great-expectations__great_expectations
great_expectations/expectations/expectation_configuration.py
{ "start": 2936, "end": 3157 }
class ____(Schema): description = fields.String(required=False, allow_none=True) @post_load def make_expectation_context(self, data, **kwargs): return ExpectationContext(**data)
ExpectationContextSchema
python
numba__numba
numba/cuda/tests/cudapy/test_lang.py
{ "start": 146, "end": 1691 }
class ____(CUDATestCase): def test_enumerate(self): tup = (1., 2.5, 3.) @cuda.jit("void(float64[:])") def foo(a): for i, v in enumerate(tup): a[i] = v a = np.zeros(len(tup)) foo[1, 1](a) self.assertTrue(np.all(a == tup)) def test_zip...
TestLang
python
getsentry__sentry
src/sentry/discover/translation/mep_to_eap.py
{ "start": 498, "end": 638 }
class ____(TypedDict): selected_columns: list[str] query: str equations: list[str] | None orderby: list[str] | None
QueryParts
python
django-extensions__django-extensions
django_extensions/management/base.py
{ "start": 135, "end": 1407 }
class ____(BaseCommand): """ A subclass of BaseCommand that logs run time errors to `django.commands`. To use this, create a management command subclassing LoggingBaseCommand: from django_extensions.management.base import LoggingBaseCommand class Command(LoggingBaseCommand): he...
LoggingBaseCommand
python
falconry__falcon
falcon/errors.py
{ "start": 77406, "end": 79748 }
class ____(HTTPError): """504 Gateway Timeout. The 504 (Gateway Timeout) status code indicates that the server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request. (See also: RFC 7231, Section 6.6.5...
HTTPGatewayTimeout
python
scipy__scipy
scipy/fftpack/tests/test_real_transforms.py
{ "start": 8547, "end": 8686 }
class ____(_TestDCTIBase): def setup_method(self): self.rdt = np.float32 self.dec = 4 self.type = 1
TestDCTIFloat
python
google__pytype
pytype/imports/module_loader.py
{ "start": 3087, "end": 5064 }
class ____(base.ModuleLoader): """Find and read module type information.""" def __init__(self, options: config.Options): self.options = options self._path_finder = _PathFinder(options) def find_import(self, module_name: str) -> base.ModuleInfo | None: """See if the loader can find a file to import f...
ModuleLoader
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/maximum_tito_depth.py
{ "start": 880, "end": 1272 }
class ____: def tito(self, parameter): ... def tito_obscure(x): # Obscure calls are treated as tito depth 0. c = C() return c.tito(x) def tito_four(x): # Ignored because too far. return tito_three(x) def issue(): x = _test_source() y = tito_three(x) _test_sink(y) def ...
C
python
wandb__wandb
landfill/functional_tests/torch/t3_ddp_basic.py
{ "start": 587, "end": 1959 }
class ____(nn.Module): def __init__(self): super().__init__() self.net1 = nn.Linear(10, 10) self.relu = nn.ReLU() self.net2 = nn.Linear(10, 5) def forward(self, x): return self.net2(self.relu(self.net1(x))) def demo_basic(rank, world_size): print(f"Running basic DD...
ToyModel
python
astropy__astropy
astropy/cosmology/_src/tests/io/test_html.py
{ "start": 476, "end": 8675 }
class ____(ReadWriteTestMixinBase): """ Tests for a Cosmology[Read/Write] with ``format="ascii.html"``. This class will not be directly called by :mod:`pytest` since its name does not begin with ``Test``. To activate the contained tests this class must be inherited in a subclass. Subclasses must def...
ReadWriteHTMLTestMixin
python
django__django
tests/forms_tests/widget_tests/test_input.py
{ "start": 71, "end": 722 }
class ____(WidgetTest): def test_attrs_with_type(self): attrs = {"type": "date"} widget = Input(attrs) self.check_html( widget, "name", "value", '<input type="date" name="name" value="value">' ) # reuse the same attrs for another widget self.check_html( ...
InputTests
python
getsentry__sentry
tests/sentry/integrations/github_enterprise/test_webhooks.py
{ "start": 11263, "end": 21503 }
class ____(APITestCase): def setUp(self) -> None: self.url = "/extensions/github-enterprise/webhook/" self.metadata = { "url": "35.232.149.196", "id": "2", "name": "test-app", "webhook_secret": "b3002c3e321d4b7880360d397db2ccfd", "private_k...
PushEventWebhookTest
python
getsentry__sentry
src/sentry/db/models/fields/bounded.py
{ "start": 2019, "end": 2396 }
class ____(models.BigIntegerField): description = _("Big Integer") MAX_VALUE = I64_MAX def get_internal_type(self) -> str: return "BigIntegerField" def get_prep_value(self, value: int) -> int: if value: value = int(value) assert value <= self.MAX_VALUE ...
BoundedBigIntegerField
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/class_methods.py
{ "start": 316, "end": 476 }
class ____: @classmethod def foo(cls, x) -> None: return _test_sink(x) def bar(): Test.foo(_test_source()) TInput = TypeVar("TInput")
Test
python
automl__auto-sklearn
autosklearn/evaluation/abstract_evaluator.py
{ "start": 3451, "end": 5962 }
class ____(DummyRegressor): def __init__( self, config: Configuration, random_state: Optional[Union[int, np.random.RandomState]], feat_type: Optional[FEAT_TYPE_TYPE] = None, init_params: Optional[Dict[str, Any]] = None, dataset_properties: Dict[str, Any] = {}, ...
MyDummyRegressor
python
dagster-io__dagster
python_modules/libraries/dagster-airlift/dagster_airlift/in_airflow/partition_utils.py
{ "start": 216, "end": 375 }
class ____(Enum): TIME_WINDOW = "TIME_WINDOW" STATIC = "STATIC" MULTIPARTITIONED = "MULTIPARTITIONED" DYNAMIC = "DYNAMIC"
PartitionDefinitionType
python
spyder-ide__spyder
external-deps/spyder-remote-services/spyder_remote_services/services/files/compression.py
{ "start": 31636, "end": 31687 }
class ____(ZipValueError): pass
ZipIntegrityError
python
django__django
tests/utils_tests/test_decorators.py
{ "start": 246, "end": 585 }
class ____: def __init__(self, get_response): self.get_response = get_response def process_view(self, request, view_func, view_args, view_kwargs): pass process_view_dec = decorator_from_middleware(ProcessViewMiddleware) @process_view_dec def process_view(request): return HttpResponse() ...
ProcessViewMiddleware
python
coleifer__peewee
tests/kv.py
{ "start": 125, "end": 3820 }
class ____(DatabaseTestCase): def setUp(self): super(TestKeyValue, self).setUp() self._kvs = [] def tearDown(self): if self._kvs: self.database.drop_tables([kv.model for kv in self._kvs]) super(TestKeyValue, self).tearDown() def create_kv(self, **kwargs): ...
TestKeyValue
python
getsentry__sentry
src/sentry/core/endpoints/organization_details.py
{ "start": 28115, "end": 37405 }
class ____(serializers.Serializer): # general slug = serializers.CharField( max_length=50, help_text="The new slug for the organization, which needs to be unique.", required=False, ) name = serializers.CharField( max_length=64, help_text="The new name for the organization...
OrganizationDetailsPutSerializer
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/patch_stdout.py
{ "start": 2109, "end": 2176 }
class ____: "Sentinel value for stopping the stdout proxy."
_Done
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/solverHigherOrder6.py
{ "start": 925, "end": 1161 }
class ____(Protocol): def __call__(self, func: _T) -> _T: ... def func5(cb: Proto, names: Any): val1 = cb(cb(names)) reveal_type(val1, expected_text="Any") val2 = cb(cb(1)) reveal_type(val2, expected_text="int")
Proto
python
run-llama__llama_index
llama-index-core/llama_index/core/readers/file/base.py
{ "start": 5595, "end": 31637 }
class ____(BaseReader, ResourcesReaderMixin, FileSystemReaderMixin): """ Simple directory reader. Load files from file directory. Automatically select the best file reader given file extensions. Args: input_dir (Union[Path, str]): Path to the directory. input_files (List): List of ...
SimpleDirectoryReader
python
davidhalter__jedi
jedi/inference/value/function.py
{ "start": 13613, "end": 14427 }
class ____(BaseFunctionExecutionContext): def __init__(self, function_value, arguments): super().__init__(function_value) self._arguments = arguments def get_filters(self, until_position=None, origin_scope=None): yield FunctionExecutionFilter( self, self._value, ...
FunctionExecutionContext
python
jazzband__django-formtools
tests/wizard/namedwizardtests/tests.py
{ "start": 13029, "end": 14056 }
class ____(NamedWizardTests, TestCase): wizard_urlname = 'nwiz_session' wizard_step_1_data = { 'session_contact_wizard-current_step': 'form1', } wizard_step_data = ( { 'form1-name': 'Pony', 'form1-thirsty': '2', 'session_contact_wizard-current_step': '...
NamedSessionWizardTests
python
scipy__scipy
scipy/optimize/tests/test__numdiff.py
{ "start": 5235, "end": 22285 }
class ____: def fun_scalar_scalar(self, x): return np.sinh(x) def jac_scalar_scalar(self, x): return np.cosh(x) def fun_scalar_vector(self, x): return np.array([x[0]**2, np.tan(x[0]), np.exp(x[0])]) def jac_scalar_vector(self, x): return np.array( [2 * x[0]...
TestApproxDerivativesDense
python
openai__openai-python
src/openai/lib/_tools.py
{ "start": 815, "end": 1969 }
class ____(Dict[str, Any]): model: type[pydantic.BaseModel] def __init__(self, tool: ResponsesFunctionToolParam, model: type[pydantic.BaseModel]) -> None: super().__init__(tool) self.model = model def cast(self) -> ResponsesFunctionToolParam: return cast(ResponsesFunctionToolParam,...
ResponsesPydanticFunctionTool
python
lepture__authlib
authlib/integrations/httpx_client/oauth2_client.py
{ "start": 6808, "end": 9215 }
class ____(_OAuth2Client, httpx.Client): SESSION_REQUEST_PARAMS = HTTPX_CLIENT_KWARGS client_auth_class = OAuth2ClientAuth token_auth_class = OAuth2Auth oauth_error_class = OAuthError def __init__( self, client_id=None, client_secret=None, token_endpoint_auth_method...
OAuth2Client
python
getsentry__sentry
tests/sentry/sentry_apps/test_sentry_app_creator.py
{ "start": 6950, "end": 11316 }
class ____(TestCase): def setUp(self) -> None: self.user = self.create_user() self.org = self.create_organization(owner=self.user) self.project = self.create_project(organization=self.org) def run_creator(self, **kwargs): return SentryAppCreator( is_internal=True, ...
TestInternalCreator
python
python__mypy
mypy/fixup.py
{ "start": 1204, "end": 9118 }
class ____(NodeVisitor[None]): current_info: TypeInfo | None = None def __init__(self, modules: dict[str, MypyFile], allow_missing: bool) -> None: self.modules = modules self.allow_missing = allow_missing self.type_fixer = TypeFixer(self.modules, allow_missing) # NOTE: This method ...
NodeFixer
python
python__mypy
mypy/stubutil.py
{ "start": 16098, "end": 21871 }
class ____: """Record necessary imports during stub generation.""" def __init__(self) -> None: # module_for['foo'] has the module name where 'foo' was imported from, or None if # 'foo' is a module imported directly; # direct_imports['foo'] is the module path used when the name 'foo' was...
ImportTracker
python
matplotlib__matplotlib
lib/matplotlib/transforms.py
{ "start": 7788, "end": 23215 }
class ____(TransformNode): """ The base class of all bounding boxes. This class is immutable; `Bbox` is a mutable subclass. The canonical representation is as two points, with no restrictions on their ordering. Convenience properties are provided to get the left, bottom, right and top edges a...
BboxBase
python
tiangolo__fastapi
tests/test_pydantic_v1_v2_multifile/modelsv2.py
{ "start": 277, "end": 321 }
class ____(BaseModel): name2: str
ItemInList
python
doocs__leetcode
solution/1100-1199/1167.Minimum Cost to Connect Sticks/Solution.py
{ "start": 0, "end": 264 }
class ____: def connectSticks(self, sticks: List[int]) -> int: heapify(sticks) ans = 0 while len(sticks) > 1: z = heappop(sticks) + heappop(sticks) ans += z heappush(sticks, z) return ans
Solution
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/control_flow/cond_v2_test.py
{ "start": 50241, "end": 53674 }
class ____(test.TestCase): def testContainer(self): """Set containers outside & inside of cond_v2. Make sure the containers are set correctly for both variable creation (tested by variables.Variable) and for stateful ops (tested by FIFOQueue) """ self.skipTest("b/113048653") with ops.Graph()...
CondV2ContainerTest
python
getsentry__sentry
tests/sentry/tasks/test_groupowner.py
{ "start": 908, "end": 20473 }
class ____(TestCase): def setUp(self) -> None: self.project = self.create_project() self.repo = Repository.objects.create( organization_id=self.organization.id, name=self.organization.id ) self.release = self.create_release(project=self.project, version="v1337") s...
TestGroupOwners
python
huggingface__transformers
tests/models/perceiver/test_modeling_perceiver.py
{ "start": 38856, "end": 45599 }
class ____(unittest.TestCase): @slow def test_inference_masked_lm(self): tokenizer = PerceiverTokenizer.from_pretrained("deepmind/language-perceiver") model = PerceiverForMaskedLM.from_pretrained("deepmind/language-perceiver") model.to(torch_device) # prepare inputs text...
PerceiverModelIntegrationTest
python
PyCQA__pylint
tests/functional/d/dotted_ancestor.py
{ "start": 57, "end": 241 }
class ____(non_init_parent_called.AAAA): # [too-few-public-methods] """test dotted name in ancestors""" def __init__(self): non_init_parent_called.AAAA.__init__(self)
Aaaa
python
vyperlang__vyper
vyper/venom/analysis/available_expression.py
{ "start": 4496, "end": 7112 }
class ____: """ Class that holds available expression and provides API for handling them """ exprs: immutables.Map[_Expression, list[IRInstruction]] def __init__(self): self.exprs = immutables.Map() def __eq__(self, other) -> bool: if not isinstance(other, _AvailableExpres...
_AvailableExpressions
python
arrow-py__arrow
arrow/locales.py
{ "start": 44648, "end": 47428 }
class ____(Locale): past = "vor {0}" future = "in {0}" and_word = "und" timeframes: ClassVar[Dict[TimeFrameLiteral, str]] = { "now": "gerade eben", "second": "einer Sekunde", "seconds": "{0} Sekunden", "minute": "einer Minute", "minutes": "{0} Minuten", "...
GermanBaseLocale
python
skorch-dev__skorch
skorch/tests/test_utils.py
{ "start": 14318, "end": 17671 }
class ____: @pytest.fixture def data_from_dataset(self): from skorch.utils import data_from_dataset return data_from_dataset @pytest.fixture def data(self): X = np.arange(8).reshape(4, 2) y = np.array([1, 3, 0, 2]) return X, y @pytest.fixture def tensors...
TestDataFromDataset
python
zarr-developers__zarr-python
src/zarr/storage/_obstore.py
{ "start": 9899, "end": 10455 }
class ____(TypedDict): """Offset or suffix range requests. These requests cannot be concurrent on the Rust side, and each need their own call to `obstore.get_async`, passing in the `range` parameter. """ original_request_index: int """The positional index in the original key_ranges input""" ...
_OtherRequest
python
python-poetry__poetry
src/poetry/console/commands/cache/list.py
{ "start": 130, "end": 634 }
class ____(Command): name = "cache list" description = "List Poetry's caches." def handle(self) -> int: config = Config.create() if config.repository_cache_directory.exists(): caches = sorted(config.repository_cache_directory.iterdir()) if caches: for...
CacheListCommand
python
getsentry__sentry
src/sentry/issues/endpoints/project_ownership.py
{ "start": 1244, "end": 7013 }
class ____(serializers.Serializer): raw = serializers.CharField( required=False, allow_blank=True, help_text="Raw input for ownership configuration. See the [Ownership Rules Documentation](/product/issues/ownership-rules/) to learn more.", ) fallthrough = serializers.BooleanField( ...
ProjectOwnershipRequestSerializer
python
mlflow__mlflow
mlflow/telemetry/events.py
{ "start": 3387, "end": 3662 }
class ____(Event): name: str = "get_logged_model" @classmethod def parse(cls, arguments: dict[str, Any]) -> dict[str, Any] | None: return { "imports": [pkg for pkg in MODULES_TO_CHECK_IMPORT if pkg in sys.modules], }
GetLoggedModelEvent
python
walkccc__LeetCode
solutions/632. Smallest Range Covering Elements from K Lists/632.py
{ "start": 0, "end": 675 }
class ____: def smallestRange(self, nums: list[list[int]]) -> list[int]: minHeap = [(row[0], i, 0) for i, row in enumerate(nums)] heapq.heapify(minHeap) maxRange = max(row[0] for row in nums) minRange = heapq.nsmallest(1, minHeap)[0][0] ans = [minRange, maxRange] while len(minHeap) == len(nu...
Solution
python
mitmproxy__pdoc
test/testdata/misc.py
{ "start": 1064, "end": 1349 }
class ____: """ You can either do >>> ClassmethodLink.bar() 42 or ```python ClassmethodLink.bar() ``` neither will be linked. """ @classmethod def bar(cls): return 42 # Testing generic bases T = TypeVar("T")
ClassmethodLink
python
ansible__ansible
test/lib/ansible_test/_internal/python_requirements.py
{ "start": 1382, "end": 1683 }
class ____: """Base class for pip commands.""" def serialize(self) -> tuple[str, dict[str, t.Any]]: """Return a serialized representation of this command.""" name = type(self).__name__[3:].lower() return name, self.__dict__ @dataclasses.dataclass(frozen=True)
PipCommand
python
airbytehq__airbyte
airbyte-integrations/connectors/source-recharge/source_recharge/streams.py
{ "start": 832, "end": 5555 }
class ____(HttpStream, ABC): """ Orders Stream: https://developer.rechargepayments.com/v1-shopify?python#list-orders Notes: Using `2021-01` the: `email`, `first_name`, `last_name` columns are not available, because these are not present in `2021-11` as DEPRECATED fields. """ primary...
Orders
python
apache__airflow
kubernetes-tests/tests/kubernetes_tests/test_base.py
{ "start": 1900, "end": 16684 }
class ____: """Base class for K8S Tests.""" host: str = KUBERNETES_HOST_PORT + "/api/v2" temp_dir = Path(tempfile.gettempdir()) # Refers to global temp directory, in linux it usual "/tmp" session: requests.Session test_id: str use_fab_auth_manager: bool = os.environ.get("USE_FAB_AUTH_MANAGER",...
BaseK8STest
python
huggingface__transformers
src/transformers/models/phi4_multimodal/modeling_phi4_multimodal.py
{ "start": 31785, "end": 32841 }
class ____(nn.Module): def __init__(self, config: Phi4MultimodalAudioConfig): super().__init__() self.feed_forward_in = Phi4MultimodalAudioMLP(config) self.self_attn = Phi4MultimodalAudioAttention(config) self.conv = Phi4MultimodalAudioConvModule(config) self.feed_forward_ou...
Phi4MultimodalAudioConformerEncoderLayer
python
PyCQA__pylint
tests/functional/i/invalid/invalid_name.py
{ "start": 2667, "end": 2961 }
class ____(FooBar): tearDown = FooBar.tearDown tearDownNotInAncestor = None # [invalid-name] from enum import Enum Color = Enum('Color', [('RED', 1), ('GREEN', 2), ('BLUE', 3)]) from typing import TypedDict MyExampleType = TypedDict("MyExampleType", {"some_field": str})
FooBarSubclass
python
tornadoweb__tornado
demos/blog/blog.py
{ "start": 5176, "end": 5463 }
class ____(BaseHandler): async def get(self): entries = await self.query( "SELECT * FROM entries ORDER BY published DESC LIMIT 10" ) self.set_header("Content-Type", "application/atom+xml") self.render("feed.xml", entries=entries)
FeedHandler
python
great-expectations__great_expectations
great_expectations/data_context/types/base.py
{ "start": 8641, "end": 11991 }
class ____(SerializableDictDot): def __init__( # noqa: C901, PLR0912, PLR0913 # FIXME CoP self, name: Optional[str] = None, class_name: Optional[str] = None, module_name: Optional[str] = None, bucket: Optional[str] = None, prefix: Optional[str] = None, delimi...
AssetConfig
python
run-llama__llama_index
llama-index-integrations/callbacks/llama-index-callbacks-openinference/llama_index/callbacks/openinference/base.py
{ "start": 1150, "end": 2669 }
class ____: """ Query data with column names following the OpenInference specification. """ id: str = field( default_factory=_generate_random_id, metadata={OPENINFERENCE_COLUMN_NAME: ":id.id:"}, ) timestamp: Optional[str] = field( default=None, metadata={OPENINFERENCE_CO...
QueryData
python
pypa__installer
tests/test_sources.py
{ "start": 1978, "end": 12829 }
class ____: def test_rejects_not_okay_name(self, tmp_path): # Create an empty zipfile path = tmp_path / "not_a_valid_name.whl" with zipfile.ZipFile(str(path), "w"): pass with ( pytest.raises(ValueError, match=r"Not a valid wheel filename: .+"), Wh...
TestWheelFile
python
openai__openai-python
src/openai/types/responses/file_search_tool.py
{ "start": 1341, "end": 1870 }
class ____(BaseModel): type: Literal["file_search"] """The type of the file search tool. Always `file_search`.""" vector_store_ids: List[str] """The IDs of the vector stores to search.""" filters: Optional[Filters] = None """A filter to apply.""" max_num_results: Optional[int] = None ...
FileSearchTool
python
PrefectHQ__prefect
src/prefect/server/events/schemas/automations.py
{ "start": 15630, "end": 21199 }
class ____(PrefectBaseModel, extra="ignore"): """Defines an action a user wants to take when a certain number of events do or don't happen to the matching resources""" name: str = Field(default=..., description="The name of this automation") description: str = Field( default="", description="A ...
AutomationCore
python
pandas-dev__pandas
pandas/tests/scalar/timestamp/test_comparisons.py
{ "start": 165, "end": 10027 }
class ____: def test_compare_non_nano_dt64(self): # don't raise when converting dt64 to Timestamp in __richcmp__ dt = np.datetime64("1066-10-14") ts = Timestamp(dt) assert dt == ts def test_comparison_dt64_ndarray(self): ts = Timestamp("2021-01-01") ts2 = Timest...
TestTimestampComparison
python
keras-team__keras
keras/src/saving/serialization_lib_test.py
{ "start": 536, "end": 1198 }
class ____(keras.layers.Layer): def __init__(self, factor, dense=None, activation=None): super().__init__() self.factor = factor if dense is None: self.dense = keras.layers.Dense(1, activation=custom_fn) else: self.dense = serialization_lib.deserialize_keras_...
NestedCustomLayer
python
getsentry__sentry
src/sentry/rules/filters/assigned_to.py
{ "start": 622, "end": 2993 }
class ____(EventFilter): id = "sentry.rules.filters.assigned_to.AssignedToFilter" label = "The issue is assigned to {targetType}" prompt = "The issue is assigned to {no one/team/member}" form_fields = {"targetType": {"type": "assignee", "choices": ASSIGNEE_CHOICES}} def get_assignees(self, group: ...
AssignedToFilter
python
encode__django-rest-framework
tests/test_validation.py
{ "start": 1757, "end": 2353 }
class ____(TestCase): def test_renamed_fields_are_model_validated(self): """ Ensure fields with 'source' applied do get still get model validation. """ # We've set `required=False` on the serializer, but the model # does not have `blank=True`, so this serializer should not va...
TestPreSaveValidationExclusionsSerializer
python
kamyu104__LeetCode-Solutions
Python/count-of-matches-in-tournament.py
{ "start": 29, "end": 171 }
class ____(object): def numberOfMatches(self, n): """ :type n: int :rtype: int """ return n-1
Solution
python
celery__celery
celery/backends/database/models.py
{ "start": 2432, "end": 3494 }
class ____(ResultModelBase): """TaskSet result.""" __tablename__ = 'celery_tasksetmeta' __table_args__ = {'sqlite_autoincrement': True} id = sa.Column(DialectSpecificInteger, sa.Sequence('taskset_id_sequence'), autoincrement=True, primary_key=True) taskset_id = sa.Column(sa.Stri...
TaskSet
python
django__django
tests/auth_tests/test_mixins.py
{ "start": 1079, "end": 1292 }
class ____( PermissionRequiredMixin, LoginRequiredMixin, EmptyResponseView ): permission_required = ["auth_tests.add_customuser", "auth_tests.change_customuser"] raise_exception = True
StackedMixinsView2
python
numba__numba
numba/cuda/cudadrv/error.py
{ "start": 139, "end": 238 }
class ____(Exception): def __str__(self): return '\n'.join(map(str, self.args))
NvvmError
python
facebookresearch__faiss
tests/test_local_search_quantizer.py
{ "start": 10311, "end": 12791 }
class ____(unittest.TestCase): def test_IndexLocalSearchQuantizer(self): ds = datasets.SyntheticDataset(32, 1000, 200, 100) gt = ds.get_groundtruth(10) ir = faiss.IndexLocalSearchQuantizer(ds.d, 4, 5) ir.train(ds.get_train()) ir.add(ds.get_database()) Dref, Iref = i...
TestIndexLocalSearchQuantizer
python
huggingface__transformers
src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py
{ "start": 28776, "end": 31111 }
class ____(GradientCheckpointingLayer): def __init__(self, config: Qwen3OmniMoeAudioEncoderConfig): super().__init__() self.embed_dim = config.d_model self.self_attn = Qwen3OmniMoeAudioAttention(config) self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim) self.dropout = c...
Qwen3OmniMoeAudioEncoderLayer
python
viewflow__viewflow
viewflow/views/base.py
{ "start": 1492, "end": 1958 }
class ____(forms.Form): def __init__(self, *args, **kwargs): model = kwargs.pop("model") super().__init__(*args, **kwargs) self.fields["pk"] = forms.ModelMultipleChoiceField( queryset=model._default_manager.all(), widget=forms.MultipleHiddenInput, require...
BulkActionForm
python
PyCQA__pylint
tests/functional/s/super/super_init_not_called_extensions_py310.py
{ "start": 355, "end": 518 }
class ____(TestParent): """An implementation which should call the init of TestParent.""" def __init__(self): # [super-init-not-called] ...
TestChild
python
apache__airflow
airflow-core/src/airflow/example_dags/plugins/listener_plugin.py
{ "start": 930, "end": 1048 }
class ____(AirflowPlugin): name = "MetadataCollectionPlugin" listeners = [event_listener]
MetadataCollectionPlugin
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/super7.py
{ "start": 160, "end": 227 }
class ____: def my_method(self, value: int) -> int: ...
BaseClass
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/matchSequence1.py
{ "start": 14331, "end": 18109 }
class ____: ... AAlias = A AInt = A[int] BOrC = B | C def test_illegal_type_alias(m: object): match m: case AAlias(a=i): pass # This should generate an error because it raises an # exception at runtime. case AInt(a=i): pass # This should genera...
C
python
huggingface__transformers
src/transformers/models/informer/modular_informer.py
{ "start": 20847, "end": 21781 }
class ____(TimeSeriesTransformerDecoder): def __init__(self, config: InformerConfig): super().__init__(config) self.dropout = config.dropout self.layerdrop = config.decoder_layerdrop if config.prediction_length is None: raise ValueError("The `prediction_length` config nee...
InformerDecoder
python
walkccc__LeetCode
solutions/465. Optimal Account Balancing/465.py
{ "start": 0, "end": 647 }
class ____: def minTransfers(self, transactions: list[list[int]]) -> int: balance = [0] * 21 for u, v, amount in transactions: balance[u] -= amount balance[v] += amount debts = [b for b in balance if b] def dfs(s: int) -> int: while s < len(debts) and not debts[s]: s += 1 ...
Solution
python
realpython__materials
python-self-type/accounts_future_module.py
{ "start": 651, "end": 1658 }
class ____(BankAccount): interest_rate: float @classmethod def from_application( cls, deposit: float = 0, interest_rate: float = 1 ) -> SavingsAccount: # Generate a random seven-digit bank account number account_number = random.randint(1000000, 9999999) return cls(accoun...
SavingsAccount
python
getsentry__sentry
tests/sentry/sudo/test_forms.py
{ "start": 359, "end": 1707 }
class ____(BaseTestCase): def setUp(self) -> None: super().setUp() self.login() def test_integration_empty(self) -> None: self.assertFalse(SudoForm(self.user).is_valid()) def test_integration_invalid_password(self) -> None: self.assertFalse(SudoForm(self.user, {"password": ...
SudoFormTestCase
python
encode__django-rest-framework
rest_framework/utils/field_mapping.py
{ "start": 495, "end": 12126 }
class ____: """ Takes a dictionary with classes as keys. Lookups against this object will traverses the object's inheritance hierarchy in method resolution order, and returns the first matching value from the dictionary or raises a KeyError if nothing matches. """ def __init__(self, mapping)...
ClassLookupDict
python
scipy__scipy
scipy/stats/_continuous_distns.py
{ "start": 252001, "end": 254271 }
class ____(rv_continuous): r"""A non-central Student's t continuous random variable. %(before_notes)s Notes ----- If :math:`Y` is a standard normal random variable and :math:`V` is an independent chi-square random variable (`chi2`) with :math:`k` degrees of freedom, then .. math:: ...
nct_gen
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_with.py
{ "start": 10663, "end": 13605 }
class ____(__TestCase, ContextmanagerAssertionMixin): def testSingleArgInlineGeneratorSyntax(self): with Nested(mock_contextmanager_generator()): pass def testSingleArgBoundToNonTuple(self): m = mock_contextmanager_generator() # This will bind all the arguments to nested...
NestedNonexceptionalTestCase
python
pytorch__pytorch
tools/experimental/torchfuzz/operators/layout.py
{ "start": 181, "end": 445 }
class ____(Operator): """Base class for tensor layout operations.""" def can_produce(self, output_spec: Spec) -> bool: """All layout operations can only produce tensor outputs.""" return isinstance(output_spec, TensorSpec)
LayoutOperatorBase
python
huggingface__transformers
src/transformers/models/zoedepth/modeling_zoedepth.py
{ "start": 1268, "end": 1956 }
class ____(ModelOutput): r""" loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Classification (or regression if config.num_labels==1) loss. domain_logits (`torch.FloatTensor` of shape `(batch_size, num_domains)`): Logits for each domain (e.g. NYU an...
ZoeDepthDepthEstimatorOutput
python
pallets__quart
src/quart/testing/connections.py
{ "start": 3833, "end": 7028 }
class ____: def __init__(self, app: Quart, scope: WebsocketScope) -> None: self.accepted = False self.app = app self.headers: Headers | None = None self.response_data = bytearray() self.scope = scope self.status_code: int | None = None self._send_queue: asynci...
TestWebsocketConnection
python
networkx__networkx
networkx/readwrite/tests/test_gexf.py
{ "start": 1984, "end": 21327 }
class ____: @classmethod def setup_class(cls): cls.simple_directed_data = """<?xml version="1.0" encoding="UTF-8"?> <gexf xmlns="http://www.gexf.net/1.2draft" version="1.2"> <graph mode="static" defaultedgetype="directed"> <nodes> <node id="0" label="Hello" /> <node i...
TestGEXF
python
pytorch__pytorch
test/inductor/extension_backends/cpp/extension_codegen_backend.py
{ "start": 459, "end": 1130 }
class ____(BaseScheduling): def __init__(self, scheduler): super().__init__(scheduler) self._scheduling = cpp.CppScheduling(scheduler) def can_fuse_vertical(self, node1, node2): return True def can_fuse_horizontal(self, node1, node2): return True def group_fn(self, siz...
ExtensionScheduling
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/engine/interfaces.py
{ "start": 15718, "end": 18041 }
class ____(Enum): """Define different methods of passing typing information for bound parameters in a statement to the database driver. .. versionadded:: 2.0 """ NONE = 1 """No steps are taken to pass typing information to the database driver. This is the default behavior for databases s...
BindTyping
python
dagster-io__dagster
python_modules/libraries/dagster-docker/dagster_docker/docker_run_launcher.py
{ "start": 862, "end": 8458 }
class ____(RunLauncher, ConfigurableClass): """Launches runs in a Docker container.""" def __init__( self, inst_data: Optional[ConfigurableClassData] = None, image=None, registry=None, env_vars=None, network=None, networks=None, container_kwargs=N...
DockerRunLauncher
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-deepset/unit_tests/test_util.py
{ "start": 348, "end": 4194 }
class ____(BaseModel): simple: Simple adjacent: bool @pytest.mark.parametrize( ("obj", "key_path", "expected"), [ ({}, "a.b", None), # default fallback value is None ({"a": {"b": 5}}, "a.b", 5), ({"a": {"b": 5}}, "a.b.c", None), # fallback # Should work for Pydantic m...
Nested
python
crytic__slither
slither/detectors/operations/encode_packed.py
{ "start": 1752, "end": 3691 }
class ____(AbstractDetector): """ Detect usage of more than one dynamic type in abi.encodePacked() arguments which could to collision """ ARGUMENT = "encode-packed-collision" HELP = "ABI encodePacked Collision" IMPACT = DetectorClassification.HIGH CONFIDENCE = DetectorClassification.HIGH ...
EncodePackedCollision