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
Textualize__textual
docs/examples/guide/widgets/counter02.py
{ "start": 140, "end": 590 }
class ____(Static, can_focus=True): """A counter that can be incremented and decremented by pressing keys.""" BINDINGS = [ ("up,k", "change_count(1)", "Increment"), # (1)! ("down,j", "change_count(-1)", "Decrement"), ] count = reactive(0) def render(self) -> RenderResult: ...
Counter
python
anthropics__anthropic-sdk-python
src/anthropic/types/citations_delta.py
{ "start": 903, "end": 997 }
class ____(BaseModel): citation: Citation type: Literal["citations_delta"]
CitationsDelta
python
walkccc__LeetCode
solutions/303. Range Sum Query - Immutable/303.py
{ "start": 0, "end": 224 }
class ____: def __init__(self, nums: list[int]): self.prefix = list(itertools.accumulate(nums, initial=0)) def sumRange(self, left: int, right: int) -> int: return self.prefix[right + 1] - self.prefix[left]
NumArray
python
rapidsai__cudf
python/cudf_polars/cudf_polars/dsl/expressions/struct.py
{ "start": 726, "end": 5058 }
class ____(Expr): class Name(IntEnum): """Internal and picklable representation of polars' `StructFunction`.""" FieldByName = auto() RenameFields = auto() PrefixFields = auto() SuffixFields = auto() JsonEncode = auto() WithFields = auto() # TODO: https://git...
StructFunction
python
joke2k__faker
tests/providers/test_geo.py
{ "start": 3857, "end": 4324 }
class ____(unittest.TestCase): """Tests in addresses in the de_AT locale""" def setUp(self): self.fake = Faker("de_AT") Faker.seed(0) def test_local_latitude(self): local_latitude = self.fake.local_latitude() assert re.match(r"4[6-8]\.\d+", str(local_latitude)) def tes...
TestDeAT
python
apache__airflow
providers/sftp/tests/unit/sftp/triggers/test_sftp.py
{ "start": 1110, "end": 8258 }
class ____: def test_sftp_trigger_serialization(self): """ Asserts that the SFTPTrigger correctly serializes its arguments and classpath. """ trigger = SFTPTrigger(path="test/path/", sftp_conn_id="sftp_default", file_pattern="my_test_file") classpath, kwargs = trigger.seriali...
TestSFTPTrigger
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_length.py
{ "start": 763, "end": 835 }
class ____: def __len__(self): x = 42 return x
Length2
python
nedbat__coveragepy
tests/test_report_common.py
{ "start": 459, "end": 6255 }
class ____(CoverageTest): """Check that reporting implicitly maps paths.""" def make_files(self, data: str, settings: bool = False) -> None: """Create the test files we need for line coverage.""" src = """\ if VER == 1: print("line 2") if VER == 2: ...
ReportMapsPathsTest
python
google__pytype
pytype/tools/tool_utils_test.py
{ "start": 775, "end": 1346 }
class ____(unittest.TestCase): """Tests for tool_utils.makedirs_or_die().""" def test_make(self): with test_utils.Tempdir() as d: subdir = path_utils.join(d.path, 'some/path') tool_utils.makedirs_or_die(subdir, '') self.assertTrue(path_utils.isdir(subdir)) def test_die(self): with self...
TestMakeDirsOrDie
python
getsentry__sentry
tests/sentry/uptime/autodetect/test_ranking.py
{ "start": 4610, "end": 5269 }
class ____(UptimeTestCase): def test(self) -> None: assert get_candidate_projects_for_org(self.organization) == [] url_1 = "https://sentry.io" url_2 = "https://sentry.sentry.io" add_base_url_to_rank(self.project, url_1) assert get_candidate_projects_for_org(self.organization)...
GetCandidateProjectsForOrgTest
python
pypa__hatch
tests/backend/builders/test_wheel.py
{ "start": 141078, "end": 149849 }
class ____: def test_single_sbom_file(self, hatch, helpers, temp_dir, config_file): config_file.model.template.plugins["default"]["tests"] = False config_file.save() with temp_dir.as_cwd(): result = hatch("new", "My.App") assert result.exit_code == 0, result.output ...
TestSBOMFiles
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_backfills.py
{ "start": 21347, "end": 26317 }
class ____(TestBackfillEndpoint): @pytest.mark.parametrize( ("reprocess_behavior", "expected_dates"), [ ( "none", [ {"logical_date": "2024-01-01T00:00:00Z"}, {"logical_date": "2024-01-04T00:00:00Z"}, ...
TestCreateBackfillDryRun
python
great-expectations__great_expectations
tests/metrics/test_metric.py
{ "start": 2001, "end": 2960 }
class ____: @pytest.mark.unit def test_success(self): expected_config = MetricConfiguration( metric_name=FULLY_QUALIFIED_METRIC_NAME, metric_domain_kwargs={ "batch_id": BATCH_ID, "row_condition": None, "condition_parser": None, ...
TestMetricConfig
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/callable.py
{ "start": 0, "end": 277 }
class ____: """A callable object that behaves like a function.""" def __call__(self, arg1, arg2, **kwargs): pass def method(self, arg1, arg2): """docstring of Callable.method().""" pass function = Callable() method = function.method
Callable
python
spack__spack
lib/spack/spack/version/common.py
{ "start": 811, "end": 901 }
class ____(VersionError): """Raised for version checksum errors."""
VersionChecksumError
python
PyCQA__pylint
tests/functional/m/member/member_checks_hints.py
{ "start": 332, "end": 670 }
class ____(Parent): def __init__(self): super().__init__() self._similar # [no-member] self._really_similar # [no-member] self._paren # [no-member] # Distance is too big self._registryyyy # [no-member] # Nothing close. self._pretty_sure_this_wont_mat...
Child
python
apache__airflow
airflow-core/src/airflow/cli/cli_parser.py
{ "start": 4577, "end": 7137 }
class ____(RawTextRichHelpFormatter): """ Custom help formatter to display help message. It resolves lazy help string before printing it using rich. """ def add_argument(self, action: Action) -> None: if isinstance(action.help, lazy_object_proxy.Proxy): action.help = str(action...
LazyRichHelpFormatter
python
kevin1024__vcrpy
vcr/stubs/__init__.py
{ "start": 13610, "end": 13827 }
class ____(VCRConnection): """A Mocked class for HTTP requests""" _baseclass = HTTPConnection _protocol = "http" debuglevel = _baseclass.debuglevel _http_vsn = _baseclass._http_vsn
VCRHTTPConnection
python
kubernetes-client__python
kubernetes/client/models/v1_cluster_role_binding_list.py
{ "start": 383, "end": 7095 }
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...
V1ClusterRoleBindingList
python
pydantic__pydantic
pydantic-core/tests/serializers/test_serialize_as_any.py
{ "start": 235, "end": 16452 }
class ____(ParentModel): y: str ParentModel.__pydantic_core_schema__ = core_schema.model_schema( ParentModel, core_schema.model_fields_schema( { 'x': core_schema.model_field(core_schema.int_schema()), } ), ref='ParentModel', ) ParentModel.__pydantic_validator__ = Schema...
ChildModel
python
weaviate__weaviate-python-client
weaviate/connect/integrations.py
{ "start": 458, "end": 787 }
class ____(_IntegrationConfig): api_key: str = Field(serialization_alias="X-Cohere-Api-Key") requests_per_minute_embeddings: Optional[int] = Field( serialization_alias="X-Cohere-Ratelimit-RequestPM-Embedding" ) base_url: Optional[str] = Field(serialization_alias="X-Cohere-Baseurl")
_IntegrationConfigCohere
python
jazzband__django-oauth-toolkit
oauth2_provider/generators.py
{ "start": 348, "end": 671 }
class ____(BaseHashGenerator): def hash(self): """ Generate a client_id for Basic Authentication scheme without colon char as in https://rfc-editor.org/rfc/rfc2617.html#section-2 """ return oauthlib_generate_client_id(length=40, chars=UNICODE_ASCII_CHARACTER_SET)
ClientIdGenerator
python
falconry__falcon
tests/test_middleware.py
{ "start": 30021, "end": 32126 }
class ____(TestMiddleware): def test_error_composed_before_resp_middleware_called(self, asgi, util): mw = CaptureResponseMiddleware() app = util.create_app(asgi, middleware=mw) app.add_route('/', MiddlewareClassResource()) client = testing.TestClient(app) response = client.s...
TestErrorHandling
python
django__django
tests/logging_tests/tests.py
{ "start": 18054, "end": 18899 }
class ____(AdminScriptTestCase): """ Accessing settings in a custom logging handler does not trigger a circular import error. """ def setUp(self): super().setUp() log_config = """{ 'version': 1, 'handlers': { 'custom_handler': { 'level': 'INFO', ...
SettingsConfigTest
python
pytorch__pytorch
torch/utils/_sympy/functions.py
{ "start": 46609, "end": 47474 }
class ____(sympy.Function): is_integer = True @classmethod def eval(cls, number): # assert number.is_integer is not True, number if number is sympy.oo: return int_oo if number is -sympy.oo: return -int_oo if isinstance(number, sympy.Number): ...
RoundToInt
python
mkdocstrings__mkdocstrings
src/mkdocstrings/_internal/handlers/base.py
{ "start": 2729, "end": 19539 }
class ____: """The base handler class. Inherit from this class to implement a handler. You will have to implement the `collect` and `render` methods. You can also implement the `teardown` method, and override the `update_env` method, to add more filters to the Jinja environment, making them a...
BaseHandler
python
huggingface__transformers
src/transformers/models/mobilebert/modeling_mobilebert.py
{ "start": 16558, "end": 16978 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.intermediate = MobileBertIntermediate(config) self.output = FFNOutput(config) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: intermediate_output = self.intermediate(hidden_states) ...
FFNLayer
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 96144, "end": 96837 }
class ____(GeneratedAirbyteSource): @public def __init__(self, name: str, client_id: str, client_secret: str): """Airbyte Source for Primetric. Args: name (str): The name of the destination. client_id (str): The Client ID of your Primetric developer application. The Clie...
PrimetricSource
python
pyca__cryptography
tests/hazmat/primitives/twofactor/test_totp.py
{ "start": 522, "end": 5246 }
class ____: @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.SHA1()), skip_message="Does not support HMAC-SHA1.", ) @pytest.mark.parametrize( "params", [i for i in vectors if i["mode"] == b"SHA1"] ) def test_generate_sha1(self, backend, params): ...
TestTOTP
python
tensorflow__tensorflow
tensorflow/python/keras/layers/legacy_rnn/rnn_cell_impl.py
{ "start": 48598, "end": 48965 }
class ____(rnn_cell_wrapper_impl.DeviceWrapperBase, _RNNCellWrapperV1): def __init__(self, *args, **kwargs): # pylint: disable=useless-super-delegation super(DeviceWrapper, self).__init__(*args, **kwargs) __init__.__doc__ = rnn_cell_wrapper_impl.DeviceWrapperBase.__init__.__doc__ @tf_ex...
DeviceWrapper
python
wandb__wandb
wandb/vendor/watchdog_0_9_0/wandb_watchdog/events.py
{ "start": 5582, "end": 6025 }
class ____(FileSystemEvent): """File system event representing file creation on the file system.""" event_type = EVENT_TYPE_CREATED def __init__(self, src_path): super(FileCreatedEvent, self).__init__(src_path) def __repr__(self): return ("<%(class_name)s: src_path=%(src_path)r>" ...
FileCreatedEvent
python
huggingface__transformers
src/transformers/models/sam3/modeling_sam3.py
{ "start": 37974, "end": 39674 }
class ____(nn.Module): def __init__(self, in_channels: int, fpn_dim: int, scale_factor: float): super().__init__() self.scale_factor = scale_factor # Build the upsampling/downsampling layers based on scale factor self.scale_layers = nn.ModuleList() if scale_factor == 4.0: ...
Sam3FPNLayer
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/metadata.py
{ "start": 3145, "end": 3575 }
class ____(graphene.ObjectType): intValue = graphene.Field( graphene.Int, description="Nullable to allow graceful degrade on > 32 bit numbers" ) intRepr = graphene.NonNull( graphene.String, description="String representation of the int to support greater than 32 bit", ) clas...
GrapheneIntMetadataEntry
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-nvidia/tests/test_nvidia.py
{ "start": 898, "end": 11354 }
class ____: def __init__(self, set_env_key_to: Optional[str] = "", set_fake_key: bool = False): self.set_env_key_to = set_env_key_to self.set_fake_key = set_fake_key def __enter__(self) -> None: self.api_env_was = os.environ.get("NVIDIA_API_KEY", "") os.environ["NVIDIA_API_KEY"]...
CachedNVIDIApiKeys
python
keras-team__keras
keras/src/backend/tensorflow/export.py
{ "start": 26, "end": 792 }
class ____: def _track_layer(self, layer): # Variables in the lists below are actually part of the trackables # that get saved, because the lists are created in __init__. variables = layer.variables trainable_variables = layer.trainable_variables non_trainable_variables = lay...
TFExportArchive
python
pytorch__pytorch
test/distributed/checkpoint/test_state_dict_stager.py
{ "start": 7015, "end": 7171 }
class ____: tensor: torch.Tensor name: str values: list[float] nested: NestedTensorStruct @dataclasses.dataclass(frozen=True)
ComplexDataClass
python
allegroai__clearml
clearml/backend_api/services/v2_9/queues.py
{ "start": 37892, "end": 38154 }
class ____(Request): """ """ _service = "queues" _action = "get_default" _version = "2.9" _schema = { "additionalProperties": False, "definitions": {}, "properties": {}, "type": "object", }
GetDefaultRequest
python
mozilla__bleach
bleach/_vendor/html5lib/filters/whitespace.py
{ "start": 253, "end": 1214 }
class ____(base.Filter): """Collapses whitespace except in pre, textarea, and script elements""" spacePreserveElements = frozenset(["pre", "textarea"] + list(rcdataElements)) def __iter__(self): preserve = 0 for token in base.Filter.__iter__(self): type = token["type"] ...
Filter
python
huggingface__transformers
src/transformers/models/marian/modeling_marian.py
{ "start": 5173, "end": 10873 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__( self, embed_dim: int, num_heads: int, dropout: float = 0.0, is_decoder: bool = False, bias: bool = True, is_causal: bool = False, config: Opti...
MarianAttention
python
agronholm__apscheduler
src/apscheduler/triggers/cron/fields.py
{ "start": 4774, "end": 4863 }
class ____(BaseField, extra_compilers=(MonthRangeExpression,)): __slots__ = ()
MonthField
python
great-expectations__great_expectations
great_expectations/exceptions/exceptions.py
{ "start": 4022, "end": 4098 }
class ____(InvalidBaseYamlConfigError): pass
InvalidDataContextConfigError
python
sphinx-doc__sphinx
sphinx/jinja2glue.py
{ "start": 4583, "end": 8356 }
class ____(TemplateBridge, BaseLoader): """Interfaces the rendering environment of jinja2 for use in Sphinx.""" # TemplateBridge interface def init( self, builder: Builder, theme: Theme | None = None, dirs: list[str] | None = None, ) -> None: # create a chain of...
BuiltinTemplateLoader
python
django__django
tests/expressions/tests.py
{ "start": 106138, "end": 112747 }
class ____(SimpleTestCase): def test_resolve_output_field_positive_integer(self): connectors = [ Combinable.ADD, Combinable.MUL, Combinable.DIV, Combinable.MOD, Combinable.POW, ] for connector in connectors: with self.su...
CombinedExpressionTests
python
coleifer__peewee
playhouse/postgres_ext.py
{ "start": 12127, "end": 13101 }
class ____(Node): def __init__(self, query, array_size=None): self.query = query self.array_size = array_size self._cursor_wrapper = None def __sql__(self, ctx): return self.query.__sql__(ctx) def __iter__(self): if self._cursor_wrapper is None: self._ex...
ServerSideQuery
python
apache__airflow
providers/atlassian/jira/src/airflow/providers/atlassian/jira/hooks/jira.py
{ "start": 1254, "end": 3793 }
class ____(BaseHook): """ Jira interaction hook, a Wrapper around Atlassian Jira Python SDK. :param jira_conn_id: reference to a pre-defined Jira Connection :param proxies: Proxies to make the Jira REST API call. Optional :param api_root: root for the api requests. Optional :param api_version: ...
JiraHook
python
crytic__slither
slither/core/declarations/custom_error.py
{ "start": 337, "end": 3308 }
class ____(SourceMapping): def __init__(self, compilation_unit: "SlitherCompilationUnit") -> None: super().__init__() self._name: str = "" self._parameters: List[LocalVariable] = [] self._compilation_unit = compilation_unit self._solidity_signature: Optional[str] = None ...
CustomError
python
RaRe-Technologies__gensim
gensim/test/test_segmentation.py
{ "start": 413, "end": 2076 }
class ____(unittest.TestCase): def setUp(self): self.topics = [ array([9, 4, 6]), array([9, 10, 7]), array([5, 2, 7]) ] def test_s_one_pre(self): """Test s_one_pre segmentation.""" actual = segmentation.s_one_pre(self.topics) expected ...
TestSegmentation
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_single.py
{ "start": 83527, "end": 90921 }
class ____( AssertsCompiledSQL, fixtures.DeclarativeMappedTest ): """test new polymorphic_abstract feature added as of #9060""" __dialect__ = "default" @classmethod def setup_classes(cls): Base = cls.DeclarativeBasic class Company(Base): __tablename__ = "company" ...
AbstractPolymorphicTest
python
coleifer__peewee
setup.py
{ "start": 3934, "end": 7502 }
class ____(build_ext): def run(self): try: build_ext.run(self) except DistutilsPlatformError: raise BuildFailure() def build_extension(self, ext): try: build_ext.build_extension(self, ext) except (CCompilerError, DistutilsExecError, DistutilsP...
_PeeweeBuildExt
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/sqltypes.py
{ "start": 12837, "end": 13133 }
class ____(Integer): """A type for bigger ``int`` integers. Typically generates a ``BIGINT`` in DDL, and otherwise acts like a normal :class:`.Integer` on the Python side. """ __visit_name__ = "big_integer" _N = TypeVar("_N", bound=Union[decimal.Decimal, float])
BigInteger
python
google__jax
jax/_src/pjit.py
{ "start": 66270, "end": 132772 }
class ____: aval: Any sharding: Any format: Any committed: bool is_np_array: bool replace = replace # type: ignore @property def shape(self): return self.aval.shape @property def ndim(self): return self.aval.ndim @util.cache(max_size=4096, trace_context_in_key=False) def create_meta_ty(...
MetaTy
python
tiangolo__fastapi
docs_src/body_nested_models/tutorial008_py39.py
{ "start": 87, "end": 248 }
class ____(BaseModel): url: HttpUrl name: str @app.post("/images/multiple/") async def create_multiple_images(images: list[Image]): return images
Image
python
huggingface__transformers
src/transformers/models/llava_onevision/modular_llava_onevision.py
{ "start": 9214, "end": 9307 }
class ____(LlavaNextVideoCausalLMOutputWithPast): pass
LlavaOnevisionCausalLMOutputWithPast
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_merge_range02.py
{ "start": 315, "end": 894 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("merge_range02.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got...
TestCompareXLSXFiles
python
euske__pdfminer
pdfminer/psparser.py
{ "start": 17277, "end": 20135 }
class ____(unittest.TestCase): TESTDATA = br'''%!PS begin end " @ # /a/BCD /Some_Name /foo#5f#xbaa 0 +1 -2 .5 1.234 (abc) () (abc ( def ) ghi) (def\040\0\0404ghi) (bach\\slask) (foo\nbaa) (this % is not a comment.) (foo baa) (foo\ baa) <> <20> < 40 4020 > <abcd00 12345> func/a/b{(c)do*}def [ 1 (z) ! ] << /foo (b...
TestPSBaseParser
python
django__django
tests/urlpatterns/test_resolvers.py
{ "start": 863, "end": 1322 }
class ____(SimpleTestCase): @override_settings(ROOT_URLCONF="urlpatterns.path_urls") def test_resolver_cache_default__root_urlconf(self): # resolver for a default URLconf (passing no argument) and for the # settings.ROOT_URLCONF is the same cached object. self.assertIs(get_resolver(), ge...
ResolverCacheTests
python
google__pytype
pytype/tests/test_basic1.py
{ "start": 10826, "end": 11837 }
class ____(test_base.BaseTest): """Loop tests.""" def test_for(self): self.Check(""" for i in range(10): print(i) print("done") """) def test_break(self): self.Check(""" for i in range(10): print(i) if i == 7: break print("done") """)...
TestLoops
python
ansible__ansible
lib/ansible/modules/user.py
{ "start": 116784, "end": 123945 }
class ____(BusyBox): platform = 'Linux' distribution = 'Buildroot' def main(): ssh_defaults = dict( bits=0, type='rsa', passphrase=None, comment='ansible-generated on %s' % socket.gethostname() ) module = AnsibleModule( argument_spec=dict( state=...
Buildroot
python
pypa__pip
src/pip/_internal/req/__init__.py
{ "start": 578, "end": 3041 }
class ____: name: str def _validate_requirements( requirements: list[InstallRequirement], ) -> Generator[tuple[str, InstallRequirement], None, None]: for req in requirements: assert req.name, f"invalid to-be-installed requirement: {req}" yield req.name, req def install_given_reqs( re...
InstallationResult
python
pytest-dev__pytest
src/_pytest/fixtures.py
{ "start": 26931, "end": 30117 }
class ____(FixtureRequest): """The type of the ``request`` fixture in a fixture function requested (transitively) by a test function.""" def __init__( self, request: FixtureRequest, scope: Scope, param: Any, param_index: int, fixturedef: FixtureDef[object], ...
SubRequest
python
dask__dask
dask/dataframe/dask_expr/_repartition.py
{ "start": 13623, "end": 14601 }
class ____(Repartition): _parameters = ["frame", "freq"] def _divisions(self): freq = _map_freq_to_period_start(self.freq) try: start = self.frame.divisions[0].ceil(freq) except ValueError: start = self.frame.divisions[0] divisions = methods.tolist( ...
RepartitionFreq
python
kamyu104__LeetCode-Solutions
Python/divide-an-array-into-subarrays-with-minimum-cost-i.py
{ "start": 1423, "end": 1881 }
class ____(object): def minimumCost(self, nums): """ :type nums: List[int] :rtype: int """ def topk(a, k): result = [float("inf")]*k for x in a: for i in xrange(len(result)): if x < result[i]: ...
Solution2
python
skorch-dev__skorch
skorch/tests/test_hf.py
{ "start": 7016, "end": 11678 }
class ____(_HuggingfaceTokenizersBaseTest): """Test with (mostly) uninitialized instances of tokenizer etc. being passed """ from tokenizers import Tokenizer from tokenizers.models import BPE, WordLevel, WordPiece, Unigram from tokenizers import normalizers from tokenizers import pre_tokeni...
TestHuggingfaceTokenizerUninitialized
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/util.py
{ "start": 18317, "end": 18714 }
class ____(str): def __str__(self) -> str: lself = len(self) if lself > 500: lleft = 250 lright = 100 trunc = lself - lleft - lright return ( f"{self[0:lleft]} ... {trunc} " f"characters truncated ... {self[-lright:]}" ...
_long_statement
python
redis__redis-py
redis/event.py
{ "start": 1211, "end": 1494 }
class ____(Exception): """ Exception wrapper that adds an event object into exception context. """ def __init__(self, exception: Exception, event: object): self.exception = exception self.event = event super().__init__(exception)
EventException
python
dateutil__dateutil
src/dateutil/rrule.py
{ "start": 54400, "end": 66557 }
class ____(object): """ Parses a string representation of a recurrence rule or set of recurrence rules. :param s: Required, a string defining one or more recurrence rules. :param dtstart: If given, used as the default recurrence start if not specified in the rule string. :...
_rrulestr
python
huggingface__transformers
tests/models/fuyu/test_image_processing_fuyu.py
{ "start": 3637, "end": 21243 }
class ____(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = FuyuImageProcessor fast_image_processing_class = FuyuImageProcessorFast # Skip tests that expect pixel_values output test_cast_dtype = None def setUp(self): self.image_processor_tester = FuyuImageProcessingTe...
FuyuImageProcessorTest
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_mic_match_country_code.py
{ "start": 2305, "end": 5245 }
class ____(ColumnMapExpectation): """Expect the provided MIC (Market Identifier Code) according to country which code (ISO3166) passed in the parameters.""" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { ...
ExpectColumnValuesToBeValidMicMatchCountryCode
python
google__flatbuffers
tests/MyGame/Example2/Monster.py
{ "start": 177, "end": 1121 }
class ____(object): __slots__ = ['_tab'] @classmethod def GetRootAs(cls, buf, offset=0): n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = Monster() x.Init(buf, n + offset) return x @classmethod def GetRootAsMonster(cls, buf, offset=0): ...
Monster
python
doocs__leetcode
solution/1900-1999/1927.Sum Game/Solution.py
{ "start": 0, "end": 353 }
class ____: def sumGame(self, num: str) -> bool: n = len(num) cnt1 = num[: n // 2].count("?") cnt2 = num[n // 2 :].count("?") s1 = sum(int(x) for x in num[: n // 2] if x != "?") s2 = sum(int(x) for x in num[n // 2 :] if x != "?") return (cnt1 + cnt2) % 2 == 1 or s1 - ...
Solution
python
getsentry__sentry
tests/sentry/integrations/github/test_webhooks.py
{ "start": 39435, "end": 51013 }
class ____(APITestCase): def setUp(self) -> None: self.url = "/extensions/github/webhook/" self.secret = "b3002c3e321d4b7880360d397db2ccfd" options.set("github-app.webhook-secret", self.secret) future_expires = datetime.now().replace(microsecond=0) + timedelta(minutes=5) wi...
IssuesEventWebhookTest
python
doocs__leetcode
solution/1300-1399/1309.Decrypt String from Alphabet to Integer Mapping/Solution.py
{ "start": 0, "end": 385 }
class ____: def freqAlphabets(self, s: str) -> str: ans = [] i, n = 0, len(s) while i < n: if i + 2 < n and s[i + 2] == "#": ans.append(chr(int(s[i : i + 2]) + ord("a") - 1)) i += 3 else: ans.append(chr(int(s[i]) + ord("...
Solution
python
getsentry__sentry
src/sentry/consumers/__init__.py
{ "start": 26744, "end": 27056 }
class ____(ProcessingStrategyFactory): def __init__(self, inner: ProcessingStrategyFactory): self.inner = inner def create_with_partitions(self, commit, partitions): rv = self.inner.create_with_partitions(commit, partitions) return JoinProfiler(rv)
JoinProfilerStrategyFactoryWrapper
python
pytorch__pytorch
test/torch_np/numpy_tests/lib/test_arraypad.py
{ "start": 545, "end": 13648 }
class ____(TestCase): @xpassIfTorchDynamo_np # (reason="tuple values") def test_check_constant(self): a = np.arange(100) a = np.pad(a, (25, 20), "constant", constant_values=(10, 20)) b = np.array( [ 10, 10, 10, ...
TestConstant
python
matplotlib__matplotlib
lib/matplotlib/ticker.py
{ "start": 7457, "end": 7668 }
class ____: axis = None def set_axis(self, axis): self.axis = axis def create_dummy_axis(self, **kwargs): if self.axis is None: self.axis = _DummyAxis(**kwargs)
TickHelper
python
spack__spack
lib/spack/spack/error.py
{ "start": 6602, "end": 6697 }
class ____(SpecFilenameError): """Raised when a spec file doesn't exist."""
NoSuchSpecFileError
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/quantization_ops/quantization_ops_test.py
{ "start": 8656, "end": 9691 }
class ____(test_util.TensorFlowTestCase): @test_util.run_in_graph_and_eager_modes def test_invalid_inputs(self): inputs = constant_op.constant( np.uint8(0), shape=[3, 3, 3, 3], dtype=dtypes.quint8) ksize = [1, 1, 1, 1] strides = [1, 1, 1, 1] padding = "SAME" with self.assertRaisesRegex...
QuantizedAvgPoolingOpTest
python
django__django
tests/model_inheritance/tests.py
{ "start": 646, "end": 12606 }
class ____(TestCase): def test_abstract(self): # The Student and Worker models both have 'name' and 'age' fields on # them and inherit the __str__() method, just as with normal Python # subclassing. This is useful if you want to factor out common # information for programming purpose...
ModelInheritanceTests
python
pytorch__pytorch
torch/_higher_order_ops/schema.py
{ "start": 2186, "end": 2891 }
class ____: @staticmethod def from_hop_argument_info( arg_idx: int, arg_info: HopArgumentInfo, is_output: bool = False ) -> Any: typ = CTypeGen.from_example(arg_info.example_value) if is_output: return torch._C.Argument("", typ, None, None, False, None) alias_set...
CArgumentGen
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/sensors/batch.py
{ "start": 7032, "end": 9371 }
class ____(AwsBaseSensor[BatchClientHook]): """ Poll the state of the Batch job queue until it reaches a terminal state; fails if the queue fails. .. seealso:: For more information on how to use this sensor, take a look at the guide: :ref:`howto/sensor:BatchJobQueueSensor` :param job_q...
BatchJobQueueSensor
python
huggingface__transformers
src/transformers/models/ctrl/tokenization_ctrl.py
{ "start": 2496, "end": 6870 }
class ____(PreTrainedTokenizer): """ Construct a CTRL tokenizer. Based on Byte-Pair-Encoding. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to this superclass for more information regarding those methods. Args: vocab_file (...
CTRLTokenizer
python
scikit-learn__scikit-learn
sklearn/linear_model/_ridge.py
{ "start": 83683, "end": 91647 }
class ____(LinearModel): _parameter_constraints: dict = { "alphas": ["array-like", Interval(Real, 0, None, closed="neither")], "fit_intercept": ["boolean"], "scoring": [StrOptions(set(get_scorer_names())), callable, None], "cv": ["cv_object"], "gcv_mode": [StrOptions({"auto",...
_BaseRidgeCV
python
PrefectHQ__prefect
src/prefect/server/events/actions.py
{ "start": 12009, "end": 12491 }
class ____(Action): async def act(self, triggered_action: "TriggeredAction") -> None: event = await self.create_event(triggered_action) self._result_details["emitted_event"] = str(event.id) async with PrefectServerEventsClient() as events: await events.emit(event) @abc.abs...
EmitEventAction
python
modin-project__modin
modin/core/dataframe/base/interchange/dataframe_protocol/utils.py
{ "start": 2322, "end": 2552 }
class ____(enum.IntEnum): # noqa PR01 """Integer enum for device type codes matching DLPack.""" CPU = 1 CUDA = 2 CPU_PINNED = 3 OPENCL = 4 VULKAN = 7 METAL = 8 VPI = 9 ROCM = 10
DlpackDeviceType
python
dask__distributed
distributed/dashboard/components/scheduler.py
{ "start": 94042, "end": 105582 }
class ____(DashboardComponent): """Stacked area chart showing task groups through time""" def __init__(self, scheduler, **kwargs): self.scheduler = scheduler self.source = ColumnDataSource() # The length of timeseries to chart (in units of plugin.dt) self.npts = 180 if ...
TaskGroupProgress
python
joblib__joblib
joblib/test/test_memory.py
{ "start": 37618, "end": 37754 }
class ____(StoreBackendBase): """This backend cannot be instantiated and should raise a TypeError.""" pass
IncompleteStoreBackend
python
pyinstaller__pyinstaller
bootloader/waflib/Tools/javaw.py
{ "start": 6883, "end": 7518 }
class ____(JTask): color = 'GREEN' run_str = '${JAR} ${JARCREATE} ${TGT} ${JAROPTS}' def runnable_status(self): for t in self.run_after: if not t.hasrun: return Task.ASK_LATER if not self.inputs: try: self.inputs = [ ...
jar_create
python
davidhalter__jedi
jedi/inference/value/namespace.py
{ "start": 391, "end": 741 }
class ____(ValueNameMixin, AbstractNameDefinition): """ Accessing names for implicit namespace packages should infer to nothing. This object will prevent Jedi from raising exceptions """ def __init__(self, implicit_ns_value, string_name): self._value = implicit_ns_value self.string_n...
ImplicitNSName
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_optim_state.py
{ "start": 3152, "end": 3921 }
class ____(torch.nn.Module): """ Used to define interesting nested structure for FSDP wrapping. BlockB weight Bias bias Bias bias """ def __init__(self, in_dim: int, out_dim: int) -> None: super().__init__() assert all(v > 0 for v in (...
BlockB
python
airbytehq__airbyte
airbyte-ci/connectors/metadata_service/lib/metadata_service/models/generated/ConnectorMetadataDefinitionV0.py
{ "start": 8503, "end": 8620 }
class ____(BaseModel): class Config: extra = Extra.forbid pypi: Optional[PyPi] = None
RemoteRegistries
python
readthedocs__readthedocs.org
readthedocs/builds/migrations/0007_add-automation-rules.py
{ "start": 218, "end": 4582 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0042_increase_env_variable_value_max_length"), ("contenttypes", "0002_remove_content_type_name"), ("builds", "0006_add_config_field"), ] operations = [ migrations.CreateModel( ...
Migration
python
huggingface__transformers
src/transformers/models/lfm2_vl/modeling_lfm2_vl.py
{ "start": 5398, "end": 6411 }
class ____(BaseModelOutputWithPast): r""" past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). C...
Lfm2VlModelOutputWithPast
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/class_interval.py
{ "start": 1200, "end": 1250 }
class ____(A2): def m2(self, x): pass
C2
python
google__jax
jax/experimental/sparse/bcoo.py
{ "start": 117078, "end": 129499 }
class ____(JAXSparse): """Experimental batched COO matrix implemented in JAX Args: (data, indices) : data and indices in batched COO format. shape : shape of sparse array. Attributes: data : ndarray of shape ``[*batch_dims, nse, *dense_dims]`` containing the explicitly stored data within the s...
BCOO
python
openai__gym
tests/vector/utils.py
{ "start": 2225, "end": 2623 }
class ____(gym.Space): """Minimal custom observation space.""" def sample(self): return self.np_random.integers(0, 10, ()) def contains(self, x): return 0 <= x <= 10 def __eq__(self, other): return isinstance(other, CustomSpace) custom_spaces = [ CustomSpace(), Tuple...
CustomSpace
python
yangshun__tech-interview-handbook
apps/website/experimental/utilities/python/trie.py
{ "start": 0, "end": 2303 }
class ____(object): def __init__(self): """ Initialize your data structure here. """ self.d = {} def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ curr = self.d for char in word: ...
Trie
python
django__django
tests/tasks/test_immediate_backend.py
{ "start": 544, "end": 11169 }
class ____(SimpleTestCase): def test_using_correct_backend(self): self.assertEqual(default_task_backend, task_backends["default"]) self.assertIsInstance(task_backends["default"], ImmediateBackend) self.assertEqual(default_task_backend.alias, "default") self.assertEqual(default_task_b...
ImmediateBackendTestCase
python
pytorch__pytorch
torch/fx/proxy.py
{ "start": 18080, "end": 18165 }
class ____(ValueError): pass @compatibility(is_backward_compatible=True)
TraceError
python
django__django
tests/model_fields/test_manytomanyfield.py
{ "start": 184, "end": 3263 }
class ____(SimpleTestCase): def test_abstract_model_pending_operations(self): """ Many-to-many fields declared on abstract models should not add lazy relations to resolve relationship declared as string (#24215). """ pending_ops_before = list(apps._pending_operations.items())...
ManyToManyFieldTests
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeVarDefaultClass2.py
{ "start": 1563, "end": 1600 }
class ____(Generic[T1, T4]): ...
ClassJ