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
aimacode__aima-python
agents.py
{ "start": 28110, "end": 28340 }
class ____(Agent): holding = [] has_arrow = True killed_by = "" direction = Direction("right") def can_grab(self, thing): """Explorer can only grab gold""" return thing.__class__ == Gold
Explorer
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/history.py
{ "start": 685, "end": 2814 }
class ____(metaclass=ABCMeta): """ Base ``History`` class. This also includes abstract methods for loading/storing history. """ def __init__(self) -> None: # In memory storage for strings. self._loaded = False # History that's loaded already, in reverse order. Latest, most...
History
python
PyCQA__pylint
tests/functional/i/invalid/invalid_length/invalid_length_returned.py
{ "start": 1153, "end": 1246 }
class ____: """ Uninferable return value """ __len__ = lambda self: Missing
AmbigousLen
python
huggingface__transformers
src/transformers/models/ernie/modeling_ernie.py
{ "start": 54268, "end": 59291 }
class ____(ErniePreTrainedModel): def __init__(self, config): super().__init__(config) self.ernie = ErnieModel(config) classifier_dropout = ( config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob ) self.dropout = nn.Dr...
ErnieForMultipleChoice
python
mlflow__mlflow
mlflow/utils/async_logging/async_logging_queue.py
{ "start": 861, "end": 1312 }
class ____(enum.Enum): """Status of the async queue""" # The queue is listening to new data and logging enqueued data to MLflow. ACTIVE = 1 # The queue is not listening to new data, but still logging enqueued data to MLflow. TEAR_DOWN = 2 # The queue is neither listening to new data or logging ...
QueueStatus
python
falconry__falcon
falcon/errors.py
{ "start": 5128, "end": 6507 }
class ____(WebSocketDisconnected): """The server encountered an unexpected error.""" pass HTTPErrorKeywordArguments = Union[str, int, None] # TODO(vytas): Passing **kwargs down to HTTPError results in arg-type error in # Mypy, because it is impossible to verify that, e.g., an int value was not # erroneo...
WebSocketServerError
python
getsentry__sentry
src/sentry/users/api/endpoints/user_details.py
{ "start": 7117, "end": 7381 }
class ____(SuperuserUserSerializer): is_staff = serializers.BooleanField() is_superuser = serializers.BooleanField() class Meta: model = User fields = ("name", "username", "is_active", "is_staff", "is_superuser")
PrivilegedUserSerializer
python
django__django
tests/test_runner/test_discover_runner.py
{ "start": 1404, "end": 3990 }
class ____(SimpleTestCase): def get_parser(self): parser = ArgumentParser() DiscoverRunner.add_arguments(parser) return parser def test_parallel_default(self, *mocked_objects): result = self.get_parser().parse_args([]) self.assertEqual(result.parallel, 0) def test_p...
DiscoverRunnerParallelArgumentTests
python
getsentry__sentry
tests/sentry/workflow_engine/processors/test_delayed_workflow.py
{ "start": 25690, "end": 33478 }
class ____(TestDelayedWorkflowBase): def setUp(self) -> None: super().setUp() assert self.workflow1.when_condition_group assert self.workflow2.when_condition_group self.data_condition_groups: list[DataConditionGroup] = ( [ self.workflow1.when_condition_g...
TestGetGroupsToFire
python
doocs__leetcode
solution/3500-3599/3590.Kth Smallest Path XOR Sum/Solution.py
{ "start": 0, "end": 1528 }
class ____: def __init__(self): self.count = 0 self.children = [None, None] def add(self, num: int, delta: int, bit=17): self.count += delta if bit < 0: return b = (num >> bit) & 1 if not self.children[b]: self.children[b] = BinarySumTrie(...
BinarySumTrie
python
getsentry__responses
responses/tests/test_responses.py
{ "start": 50096, "end": 70111 }
class ____: def test_passthrough_flag(self, httpserver): httpserver.expect_request("/").respond_with_data( "OK", content_type="text/plain" ) url = httpserver.url_for("/") response = Response(responses.GET, url, body="MOCK") @responses.activate def run_pa...
TestPassthru
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance3.py
{ "start": 250, "end": 283 }
class ____: c_val: int @final
C
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 161598, "end": 162097 }
class ____(sgqlc.types.Input): """Autogenerated input type of ClosePullRequest""" __schema__ = github_schema __field_names__ = ("pull_request_id", "client_mutation_id") pull_request_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="pullRequestId") """ID of the pull request to be closed...
ClosePullRequestInput
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/control_flow/control_flow_util_v2_test.py
{ "start": 1139, "end": 2172 }
class ____(test.TestCase): def setUp(self): self._enable_control_flow_v2_old = control_flow_util.ENABLE_CONTROL_FLOW_V2 control_flow_util.ENABLE_CONTROL_FLOW_V2 = True def tearDown(self): control_flow_util.ENABLE_CONTROL_FLOW_V2 = self._enable_control_flow_v2_old def _create_control_flow(self, expe...
ControlFlowUtilV2Test
python
pytorch__pytorch
torch/fx/_symbolic_trace.py
{ "start": 7436, "end": 41822 }
class ____(TracerBase): # Reference: https://github.com/pytorch/pytorch/issues/54354 # The first line of this docstring overrides the one Sphinx generates for the # documentation. We need it so that Sphinx doesn't leak `math`s path from the # build environment (e.g. `<module 'math' from '/leaked/path')....
Tracer
python
sphinx-doc__sphinx
sphinx/domains/c/_symbol.py
{ "start": 1718, "end": 27153 }
class ____: debug_indent = 0 debug_indent_string = ' ' debug_lookup = False debug_show_tree = False def __copy__(self) -> Self: raise AssertionError # shouldn't happen def __deepcopy__(self, memo: Any) -> Symbol: if self.parent: raise AssertionError # shouldn't h...
Symbol
python
apache__airflow
providers/openlineage/src/airflow/providers/openlineage/plugins/facets.py
{ "start": 1485, "end": 2522 }
class ____(JobFacet): """ Composite Airflow job facet. This facet encapsulates all the necessary information to re-create full scope of an Airflow DAG logic, enabling reconstruction, visualization, and analysis of DAGs in a comprehensive manner. It includes detailed representations of the tasks, ta...
AirflowJobFacet
python
pytorch__pytorch
torch/testing/_internal/common_fsdp.py
{ "start": 25422, "end": 25624 }
class ____(nn.Module): def __init__(self, module): super().__init__() self.module = module def forward(self, *args, **kwargs): return self.module(*args, **kwargs)
DummyDDP
python
kamyu104__LeetCode-Solutions
Python/count-words-obtained-after-adding-a-letter.py
{ "start": 29, "end": 575 }
class ____(object): def wordCount(self, startWords, targetWords): """ :type startWords: List[str] :type targetWords: List[str] :rtype: int """ def bitmask(w): return reduce(lambda x, y: x|y, (1 << (ord(c)-ord('a')) for i, c in enumerate(w))) looku...
Solution
python
pytorch__pytorch
test/functorch/test_control_flow.py
{ "start": 370805, "end": 382608 }
class ____(TestCase): def _get_example_val(self, ty: str): from torch.fx.experimental.sym_node import SymNode from torch.fx.experimental.symbolic_shapes import ShapeEnv def create_symtype(cls, pytype, shape_env, val): from torch._dynamo.source import ConstantSource ...
TestHopSchema
python
getsentry__sentry
src/sentry/web/frontend/debug/debug_assigned_email.py
{ "start": 603, "end": 1079 }
class ____(ActivityMailDebugView): def get_activity(self, request: AuthenticatedHttpRequest, event): return { "type": ActivityType.ASSIGNED.value, "user_id": request.user.id, "data": { "assignee": str(request.user.id), "assigneeEmail": requ...
DebugSelfAssignedEmailView
python
sympy__sympy
sympy/polys/agca/modules.py
{ "start": 42516, "end": 42821 }
class ____(ModuleElement): """Element of a quotient module.""" def eq(self, d1, d2): """Equality comparison.""" return self.module.killed_module.contains(d1 - d2) def __repr__(self): return repr(self.data) + " + " + repr(self.module.killed_module)
QuotientModuleElement
python
PrefectHQ__prefect
tests/runtime/test_flow_run.py
{ "start": 7680, "end": 8585 }
class ____: async def test_name_is_attribute(self): assert "name" in dir(flow_run) async def test_name_is_empty_when_not_set(self): assert flow_run.name is None async def test_name_returns_name_when_present_dynamically(self): assert flow_run.name is None with FlowRunContex...
TestName
python
encode__django-rest-framework
tests/test_permissions.py
{ "start": 1209, "end": 1502 }
class ____(generics.ListCreateAPIView): serializer_class = BasicSerializer authentication_classes = [authentication.BasicAuthentication] permission_classes = [permissions.DjangoModelPermissions] def get_queryset(self): return BasicModel.objects.all()
GetQuerySetListView
python
readthedocs__readthedocs.org
readthedocs/builds/migrations/0011_version-media-availability.py
{ "start": 150, "end": 893 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("builds", "0010_add-description-field-to-automation-rule"), ] operations = [ migrations.AddField( model_name="version", name="has_epub", field=models.BooleanField(default=F...
Migration
python
pydantic__pydantic
pydantic-core/python/pydantic_core/core_schema.py
{ "start": 78411, "end": 82924 }
class ____(TypedDict, total=False): type: Required[Literal['function-wrap']] function: Required[WrapValidatorFunction] schema: Required[CoreSchema] ref: str json_schema_input_schema: CoreSchema metadata: dict[str, Any] serialization: SerSchema def no_info_wrap_validator_function( funct...
WrapValidatorFunctionSchema
python
langchain-ai__langchain
libs/langchain_v1/tests/unit_tests/agents/test_system_message.py
{ "start": 16130, "end": 20845 }
class ____: """Test multiple middleware modifying system message in sequence.""" def test_multiple_middleware_can_chain_modifications(self) -> None: """Test that multiple middleware can modify system message sequentially.""" def first_middleware(request: ModelRequest, handler) -> ModelResponse...
TestMultipleMiddlewareChaining
python
great-expectations__great_expectations
great_expectations/expectations/metrics/column_aggregate_metrics/column_histogram.py
{ "start": 1011, "end": 10631 }
class ____(ColumnAggregateMetricProvider): metric_name = "column.histogram" value_keys = ("bins",) @metric_value(engine=PandasExecutionEngine) def _pandas( cls, execution_engine: PandasExecutionEngine, metric_domain_kwargs: dict, metric_value_kwargs: dict, metric...
ColumnHistogram
python
huggingface__transformers
tests/quantization/vptq_integration/test_vptq.py
{ "start": 1524, "end": 7175 }
class ____(unittest.TestCase): model_name = "VPTQ-community/Meta-Llama-3.1-8B-Instruct-v12-k65536-4096-woft" input_text = "Hello my name is" max_new_tokens = 32 EXPECTED_OUTPUT = "Hello my name is Sarah and I am a 25 year old woman from the United States. I am a college graduate and I am currently wor...
VptqTest
python
pytorch__pytorch
torch/ao/pruning/_experimental/pruner/parametrization.py
{ "start": 1472, "end": 2047 }
class ____: def __init__(self, parametrization, prune_bias): self.param = parametrization self.prune_bias = prune_bias def __call__(self, module, input, output): if getattr(module, "_bias", None) is not None: bias = module._bias.data if self.prune_bias: ...
BiasHook
python
langchain-ai__langchain
libs/langchain/langchain_classic/agents/agent_toolkits/vectorstore/toolkit.py
{ "start": 553, "end": 2071 }
class ____(BaseToolkit): """Toolkit for interacting with a `VectorStore`.""" vectorstore_info: VectorStoreInfo = Field(exclude=True) llm: BaseLanguageModel model_config = ConfigDict( arbitrary_types_allowed=True, ) def get_tools(self) -> list[BaseTool]: """Get the tools in the...
VectorStoreToolkit
python
pallets__jinja
src/jinja2/nodes.py
{ "start": 27859, "end": 27947 }
class ____(BinExpr): """Divides the left by the right node.""" operator = "/"
Div
python
celery__celery
t/unit/utils/test_serialization.py
{ "start": 487, "end": 910 }
class ____: @pytest.mark.masked_modules('cPickle') def test_no_cpickle(self, mask_modules): prev = sys.modules.pop('celery.utils.serialization', None) try: import pickle as orig_pickle from celery.utils.serialization import pickle assert pickle.dumps is orig...
test_AAPickle
python
PrefectHQ__prefect
src/integrations/prefect-kubernetes/prefect_kubernetes/worker.py
{ "start": 6928, "end": 22974 }
class ____(BaseJobConfiguration): """ Configuration class used by the Kubernetes worker. An instance of this class is passed to the Kubernetes worker's `run` method for each flow run. It contains all of the information necessary to execute the flow run as a Kubernetes job. Attributes: ...
KubernetesWorkerJobConfiguration
python
arrow-py__arrow
tests/test_arrow.py
{ "start": 53173, "end": 55282 }
class ____: def test_incorrect_input(self): with pytest.raises(ValueError): list( arrow.Arrow.interval( "month", datetime(2013, 1, 2), datetime(2013, 4, 15), 0 ) ) def test_correct(self): result = list( arro...
TestArrowInterval
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-oceanbase/llama_index/vector_stores/oceanbase/base.py
{ "start": 2199, "end": 19401 }
class ____(BasePydanticVectorStore): """ OceanBase Vector Store. You need to install `pyobvector` and run a standalone observer or OceanBase cluster. See the following documentation for how to deploy OceanBase: https://github.com/oceanbase/oceanbase-doc/blob/V4.3.1/en-US/400.deploy/500.deploy-ocea...
OceanBaseVectorStore
python
Netflix__metaflow
metaflow/exception.py
{ "start": 2614, "end": 2693 }
class ____(MetaflowException): headline = "Object not found"
MetaflowNotFound
python
pypa__warehouse
tests/unit/admin/views/test_malware_reports.py
{ "start": 1126, "end": 6647 }
class ____: def test_malware_reports_project_list(self, db_request): project = ProjectFactory.create() assert views.malware_reports_project_list(project, db_request) == { "project": project, "malware_reports": [], } def test_malware_reports_project_list_with_proj...
TestMalwareReportsProjectList
python
django__django
tests/db_functions/text/test_length.py
{ "start": 195, "end": 1694 }
class ____(TestCase): def test_basic(self): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") authors = Author.objects.annotate( name_length=Length("name"), alias_length=Length("alias"), ) self.assertQuerySet...
LengthTests
python
doocs__leetcode
solution/2500-2599/2533.Number of Good Binary Strings/Solution.py
{ "start": 0, "end": 440 }
class ____: def goodBinaryStrings( self, minLength: int, maxLength: int, oneGroup: int, zeroGroup: int ) -> int: mod = 10**9 + 7 f = [1] + [0] * maxLength for i in range(1, len(f)): if i - oneGroup >= 0: f[i] += f[i - oneGroup] if i - zeroG...
Solution
python
keras-team__keras
keras/src/layers/preprocessing/image_preprocessing/random_elastic_transform.py
{ "start": 304, "end": 10208 }
class ____(BaseImagePreprocessingLayer): """A preprocessing layer that applies random elastic transformations. This layer distorts input images by applying elastic deformations, simulating a physically realistic transformation. The magnitude of the distortion is controlled by the `scale` parameter, whi...
RandomElasticTransform
python
davidhalter__jedi
jedi/inference/compiled/access.py
{ "start": 4059, "end": 4652 }
class ____: def __init__(self, accesses): self.accesses = accesses def create_access_path(inference_state, obj) -> AccessPath: access = create_access(inference_state, obj) return AccessPath(access.get_access_path_tuples()) def get_api_type(obj): if inspect.isclass(obj): return 'class...
AccessPath
python
django__django
tests/field_defaults/models.py
{ "start": 738, "end": 1317 }
class ____(models.Model): """ Values or expressions can be passed as the db_default parameter to a field. When the object is created without an explicit value passed in, the database will insert the default value automatically. """ headline = models.CharField(max_length=100, db_default="Default...
DBArticle
python
huggingface__transformers
src/transformers/models/instructblipvideo/video_processing_instructblipvideo.py
{ "start": 1082, "end": 3765 }
class ____(BaseVideoProcessor): resample = PILImageResampling.BICUBIC image_mean = OPENAI_CLIP_MEAN image_std = OPENAI_CLIP_STD size = {"height": 384, "width": 384} default_to_square = True do_resize = True do_rescale = True do_normalize = True do_convert_rgb = True do_sample_fra...
InstructBlipVideoVideoProcessor
python
PrefectHQ__prefect
src/prefect/events/clients.py
{ "start": 24221, "end": 25132 }
class ____(PrefectCloudEventSubscriber): def __init__( self, api_url: Optional[str] = None, api_key: Optional[str] = None, filter: Optional["EventFilter"] = None, reconnection_attempts: int = 10, ): """ Args: api_url: The base URL for a Prefect...
PrefectCloudAccountEventSubscriber
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/asyncpg.py
{ "start": 9963, "end": 10035 }
class ____(sqltypes.DateTime): render_bind_cast = True
AsyncpgDateTime
python
huggingface__transformers
src/transformers/models/sam3/configuration_sam3.py
{ "start": 7796, "end": 9934 }
class ____(PreTrainedConfig): r""" Configuration class for SAM3 Geometry Encoder. Args: hidden_size (`int`, *optional*, defaults to 256): Dimensionality of the encoder layers. num_layers (`int`, *optional*, defaults to 3): Number of transformer encoder layers for pro...
Sam3GeometryEncoderConfig
python
spack__spack
lib/spack/spack/modules/lmod.py
{ "start": 3226, "end": 9507 }
class ____(BaseConfiguration): """Configuration class for lmod module files.""" default_projections = {"all": "{name}/{version}"} compiler: Optional[spack.spec.Spec] def __init__(self, spec: spack.spec.Spec, module_set_name: str, explicit: bool) -> None: super().__init__(spec, module_set_name...
LmodConfiguration
python
bokeh__bokeh
src/bokeh/sphinxext/_internal/bokeh_enum.py
{ "start": 2140, "end": 3904 }
class ____(BokehDirective): has_content = True required_arguments = 1 option_spec = { "module": unchanged, "noindex": lambda x: True, # directives.flag weirdly returns None } def run(self): enum_name = self.arguments[0] module_name = self.options["module"] ...
BokehEnumDirective
python
bokeh__bokeh
src/bokeh/models/annotations/geometry.py
{ "start": 16025, "end": 17354 }
class ____(Annotation): """ Render a horizontal or vertical line span. See :ref:`ug_basic_annotations_spans` for information on plotting spans. """ # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) ...
Span
python
getsentry__sentry
tests/sentry/workflow_engine/migrations/test_0085_crons_link_detectors_to_all_workflows.py
{ "start": 313, "end": 8427 }
class ____(TestMigrations): migrate_from = "0084_crons_dedupe_workflows" migrate_to = "0085_crons_link_detectors_to_all_workflows" app = "workflow_engine" def setup_initial_state(self) -> None: # Create organizations and projects self.org1 = self.create_organization(name="org1") ...
LinkCronDetectorsToAllWorkflowsTest
python
spack__spack
lib/spack/spack/patch.py
{ "start": 5112, "end": 7953 }
class ____(Patch): """Describes a patch that is retrieved from a file in the repository.""" _sha256: Optional[str] = None def __init__( self, pkg: PatchPackageType, relative_path: str, level: int, working_dir: str, reverse: bool = False, ordering_key...
FilePatch
python
huggingface__transformers
src/transformers/models/recurrent_gemma/modeling_recurrent_gemma.py
{ "start": 1528, "end": 2323 }
class ____(nn.Module): def __init__(self, dim: int, eps: float = 1e-6): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.zeros(dim)) def _norm(self, x): return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) def forward(self, x): output...
RecurrentGemmaRMSNorm
python
allegroai__clearml
clearml/utilities/pyhocon/exceptions.py
{ "start": 163, "end": 231 }
class ____(ConfigException, KeyError): pass
ConfigMissingException
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_lookup.py
{ "start": 13880, "end": 13943 }
class ____: def __init__(self, arg): pass
UnknownType
python
walkccc__LeetCode
solutions/1488. Avoid Flood in The City/1488.py
{ "start": 41, "end": 1028 }
class ____: def avoidFlood(self, rains: list[int]) -> list[int]: ans = [-1] * len(rains) lakeIdToFullDay = {} emptyDays = SortedSet() # indices of rains[i] == 0 for i, lakeId in enumerate(rains): if lakeId == 0: emptyDays.add(i) continue # The lake was full in a previou...
Solution
python
huggingface__transformers
tests/models/glm4/test_modeling_glm4.py
{ "start": 1272, "end": 1475 }
class ____(CausalLMModelTest, unittest.TestCase): model_tester_class = Glm4ModelTester _is_stateful = True model_split_percents = [0.5, 0.6] @slow @require_torch_large_accelerator
Glm4ModelTest
python
jd__tenacity
tenacity/retry.py
{ "start": 8738, "end": 9032 }
class ____(retry_base): """Retries if all the retries condition are valid.""" def __init__(self, *retries: retry_base) -> None: self.retries = retries def __call__(self, retry_state: "RetryCallState") -> bool: return all(r(retry_state) for r in self.retries)
retry_all
python
pypa__warehouse
warehouse/accounts/models.py
{ "start": 11011, "end": 11666 }
class ____(db.Model): __tablename__ = "user_security_keys" __table_args__ = ( UniqueConstraint("label", "user_id", name="_user_security_keys_label_uc"), ) user_id: Mapped[UUID] = mapped_column( PG_UUID(as_uuid=True), ForeignKey("users.id", deferrable=True, initially="DEFERRED"),...
WebAuthn
python
charliermarsh__ruff
crates/ty_python_semantic/resources/corpus/71_class_meth.py
{ "start": 0, "end": 43 }
class ____: def foo(self): self
C
python
django__django
tests/template_tests/syntax_tests/i18n/test_translate.py
{ "start": 10367, "end": 11900 }
class ____(MultipleLocaleActivationTestCase): tag_name = "trans" def get_template(self, template_string): return Template( template_string.replace("{{% translate ", "{{% {}".format(self.tag_name)) ) def test_single_locale_activation(self): """ Simple baseline be...
MultipleLocaleActivationTransTagTests
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_dtype.py
{ "start": 10766, "end": 11189 }
class ____(TestCase): def test_dtypes_are_true(self): # test for gh-6294 assert bool(np.dtype("f8")) assert bool(np.dtype("i8")) @xpassIfTorchDynamo_np # (reason="No keyword arg for dtype ctor.") def test_keyword_argument(self): # test for https://github.com/numpy/numpy/pul...
TestMisc
python
PyCQA__pycodestyle
pycodestyle.py
{ "start": 83883, "end": 84011 }
class ____(BaseReport): """Collect the results of the checks and print the filenames.""" print_filename = True
FileReport
python
django__django
tests/invalid_models_tests/test_models.py
{ "start": 64072, "end": 64568 }
class ____(TestCase): def test_multiple_autofields(self): msg = ( "Model invalid_models_tests.MultipleAutoFields can't have more " "than one auto-generated field." ) with self.assertRaisesMessage(ValueError, msg): class MultipleAutoFields(models.Model): ...
MultipleAutoFieldsTests
python
realpython__materials
langchain-rag-app/source_code_final/chatbot_api/src/models/hospital_rag_query.py
{ "start": 86, "end": 189 }
class ____(BaseModel): input: str output: str intermediate_steps: list[str]
HospitalQueryOutput
python
tensorflow__tensorflow
tensorflow/python/trackable/base.py
{ "start": 9399, "end": 42402 }
class ____(object): """Base class for `Trackable` objects without automatic dependencies. This class has no __setattr__ override for performance reasons. Dependencies must be added explicitly. Unless attribute assignment is performance-critical, use `AutoTrackable` instead. Use `Trackable` for `isinstance` c...
Trackable
python
kamyu104__LeetCode-Solutions
Python/heaters.py
{ "start": 122, "end": 799 }
class ____(object): def findRadius(self, houses, heaters): """ :type houses: List[int] :type heaters: List[int] :rtype: int """ heaters.sort() min_radius = 0 for house in houses: equal_or_larger = bisect.bisect_left(heaters, house) cu...
Solution
python
django__django
tests/invalid_models_tests/test_ordinary_fields.py
{ "start": 32556, "end": 34956 }
class ____(SimpleTestCase): maxDiff = None def test_fix_default_value(self): class Model(models.Model): field_dt = models.TimeField(default=now()) field_t = models.TimeField(default=now().time()) # Timezone-aware time object (when USE_TZ=True). field_tz =...
TimeFieldTests
python
pytorch__pytorch
torch/_inductor/codegen/wrapper.py
{ "start": 15064, "end": 15357 }
class ____(WrapperLine): line: LineContext def codegen(self, code: IndentedBuffer) -> None: code.writeline(self.line) @staticmethod def codegen_fx(converter: FxConverter) -> FxConversionFunc: return converter._generate_comment @dataclasses.dataclass
CommentLine
python
langchain-ai__langchain
libs/partners/openai/langchain_openai/middleware/openai_moderation.py
{ "start": 732, "end": 1434 }
class ____(RuntimeError): """Raised when OpenAI flags content and `exit_behavior` is set to ``"error"``.""" def __init__( self, *, content: str, stage: ViolationStage, result: Moderation, message: str, ) -> None: """Initialize the error with violation...
OpenAIModerationError
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 374244, "end": 376079 }
class ____(sgqlc.types.Input): """Autogenerated input type of UpdateSponsorshipPreferences""" __schema__ = github_schema __field_names__ = ( "sponsor_id", "sponsor_login", "sponsorable_id", "sponsorable_login", "receive_emails", "privacy_level", "clie...
UpdateSponsorshipPreferencesInput
python
charliermarsh__ruff
crates/ruff_python_ast/generate.py
{ "start": 2932, "end": 3618 }
class ____: name: str nodes: list[Node] owned_enum_ty: str add_suffix_to_is_methods: bool anynode_is_label: str doc: str | None def __init__(self, group_name: str, group: dict[str, Any]) -> None: self.name = group_name self.owned_enum_ty = group_name self.ref_enum_t...
Group
python
huggingface__transformers
src/transformers/models/xmod/modeling_xmod.py
{ "start": 18389, "end": 20709 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.ln_before_adapter = config.ln_before_adapter self.dropo...
XmodOutput
python
pallets__werkzeug
src/werkzeug/routing/rules.py
{ "start": 7436, "end": 9885 }
class ____(RuleFactory): """A factory that fills in template variables into rules. Used by `RuleTemplate` internally. :internal: """ def __init__( self, rules: t.Iterable[RuleFactory], context: dict[str, t.Any] ) -> None: self.rules = rules self.context = context ...
RuleTemplateFactory
python
cython__cython
Cython/Debugger/libpython.py
{ "start": 91497, "end": 92866 }
class ____(gdb.Command): def readcode(self, expr): if expr: return expr, PythonCodeExecutor.Py_single_input else: lines = [] while True: try: line = input('>') except EOFError: break ...
PyExec
python
networkx__networkx
networkx/algorithms/tree/tests/test_mst.py
{ "start": 466, "end": 8826 }
class ____: """Base class for test classes for minimum spanning tree algorithms. This class contains some common tests that will be inherited by subclasses. Each subclass must have a class attribute :data:`algorithm` that is a string representing the algorithm to run, as described under the ``algori...
MinimumSpanningTreeTestBase
python
getsentry__sentry
tests/sentry/sentry_apps/api/endpoints/test_sentry_app_components.py
{ "start": 762, "end": 2001 }
class ____(APITestCase): endpoint = "sentry-api-0-sentry-app-components" def setUp(self) -> None: self.superuser = self.create_user(email="a@example.com", is_superuser=True) self.user = self.create_user(email="boop@example.com") self.org = self.create_organization(owner=self.user) ...
SentryAppComponentsTest
python
kamyu104__LeetCode-Solutions
Python/inorder-successor-in-bst-ii.py
{ "start": 54, "end": 238 }
class ____(object): def __init__(self, val, left, right, parent): self.val = val self.left = left self.right = right self.parent = parent
Node
python
sqlalchemy__sqlalchemy
test/orm/declarative/test_mixin.py
{ "start": 65967, "end": 78214 }
class ____(DeclarativeTestBase, testing.AssertsCompiledSQL): __dialect__ = "default" def test_singleton_behavior_within_decl(self): counter = mock.Mock() class Mixin: @declared_attr def my_prop(cls): counter(cls) return Column("x", Intege...
DeclaredAttrTest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/util/langhelpers.py
{ "start": 60276, "end": 67810 }
class ____: r"""Apply translation of functions to accept \**kw arguments if they don't already. Used to ensure cross-compatibility with third party legacy code, for things like compiler visit methods that need to accept ``**kw`` arguments, but may have been copied from old code that didn't accept t...
EnsureKWArg
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/memberAccess3.py
{ "start": 263, "end": 323 }
class ____(A): def __init__(self): self.y = "hi"
B
python
doocs__leetcode
solution/3000-3099/3075.Maximize Happiness of Selected Children/Solution.py
{ "start": 0, "end": 254 }
class ____: def maximumHappinessSum(self, happiness: List[int], k: int) -> int: happiness.sort(reverse=True) ans = 0 for i, x in enumerate(happiness[:k]): x -= i ans += max(x, 0) return ans
Solution
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/strategy_options.py
{ "start": 52005, "end": 63002 }
class ____( cache_key.HasCacheKey, traversals.HasShallowCopy, visitors.Traversible ): """represents strategy information to select for a LoaderStrategy and pass options to it. :class:`._LoadElement` objects provide the inner datastructure stored by a :class:`_orm.Load` object and are also the objec...
_LoadElement
python
spyder-ide__spyder
external-deps/spyder-kernels/spyder_kernels/utils/pythonenv.py
{ "start": 725, "end": 3910 }
class ____(TypedDict): """Schema for Python environment information.""" path: str env_type: PythonEnvType name: str python_version: str # These keys are necessary to build the console banner in Spyder ipython_version: str sys_version: str def add_quotes(path): """Return quotes if...
PythonEnvInfo
python
spyder-ide__spyder
spyder/widgets/config.py
{ "start": 2483, "end": 46022 }
class ____(SidebarPage, ConfigAccessMixin): """ Page that can display graphical elements connected to our config system. """ # Signals apply_button_enabled = Signal(bool) # Constants CONF_SECTION = None LOAD_FROM_CONFIG = True def __init__(self, parent): SidebarPage.__init...
SpyderConfigPage
python
MongoEngine__mongoengine
tests/fields/test_enum_field.py
{ "start": 5765, "end": 6182 }
class ____(MongoDBTestCase): def test_enum_incompatible_bson_type_fails_during_save(self): class FunkyColor(Enum): YELLOW = object() class ModelWithFunkyColor(Document): color = EnumField(FunkyColor) m = ModelWithFunkyColor(color=FunkyColor.YELLOW) with pyt...
TestFunkyEnumField
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/ext/associationproxy.py
{ "start": 10921, "end": 11096 }
class ____(Protocol[_T]): def __call__( self, ) -> Union[ MutableSet[_T], MutableMapping[Any, _T], MutableSequence[_T] ]: ...
_LazyCollectionProtocol
python
python-pillow__Pillow
src/PIL/DdsImagePlugin.py
{ "start": 903, "end": 990 }
class ____(IntFlag): COMPLEX = 0x8 TEXTURE = 0x1000 MIPMAP = 0x400000
DDSCAPS
python
ray-project__ray
python/ray/_common/formatters.py
{ "start": 3939, "end": 4585 }
class ____(AbstractFormatter): def __init__(self, fmt=None, datefmt=None, style="%", validate=True) -> None: super().__init__(fmt, datefmt, style, validate) self._inner_formatter = logging.Formatter(LOGGER_FORMAT) def format(self, record: logging.LogRecord) -> str: s = self._inner_forma...
TextFormatter
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_database_backend.py
{ "start": 12703, "end": 22890 }
class ____(RuleBasedStateMachine): """ This is a state machine that tests agreement of GitHubArtifactDatabase with DirectoryBasedExampleDatabase (as a reference implementation). """ def __init__(self): super().__init__() self.temp_directory = Path(tempfile.mkdtemp()) self.pa...
GitHubArtifactMocks
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/model_query_transitive_extends.py
{ "start": 609, "end": 668 }
class ____: def foo(self, attribute): ...
Test2_C
python
pytorch__pytorch
torch/nn/modules/loss.py
{ "start": 37225, "end": 40375 }
class ____(_Loss): r"""Measures the loss given an input tensor :math:`x` and a labels tensor :math:`y` (containing 1 or -1). This is usually used for measuring whether two inputs are similar or dissimilar, e.g. using the L1 pairwise distance as :math:`x`, and is typically used for learning nonlinear...
HingeEmbeddingLoss
python
apache__airflow
task-sdk/tests/task_sdk/execution_time/test_task_runner.py
{ "start": 116430, "end": 131270 }
class ____: class _Failure(Exception): """Exception raised in a failed execution and received by the failure callback.""" def _execute_success(self, context): self.results.append("execute success") def _execute_skipped(self, context): from airflow.sdk.exceptions import AirflowSkipE...
TestTaskRunnerCallsCallbacks
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pep8_naming/ignore_names/N804.py
{ "start": 26, "end": 246 }
class ____: def __init_subclass__(self, default_name, **kwargs): ... @classmethod def badAllowed(self, x, /, other): ... @classmethod def stillBad(self, x, /, other): ...
Class
python
ray-project__ray
rllib/examples/envs/classes/fast_image_env.py
{ "start": 88, "end": 574 }
class ____(gym.Env): def __init__(self, config): self.zeros = np.zeros((84, 84, 4)) self.action_space = Discrete(2) self.observation_space = Box(0.0, 1.0, shape=(84, 84, 4), dtype=np.float32) self.i = 0 def reset(self, *, seed=None, options=None): self.i = 0 retu...
FastImageEnv
python
numpy__numpy
numpy/distutils/npy_pkg_config.py
{ "start": 1857, "end": 3943 }
class ____: """ Object containing build information about a library. Parameters ---------- name : str The library name. description : str Description of the library. version : str Version string. sections : dict The sections of the configuration file for ...
LibraryInfo
python
matplotlib__matplotlib
lib/matplotlib/sphinxext/plot_directive.py
{ "start": 12507, "end": 17031 }
class ____(EnvironmentCollector): def process_doc(self, app, doctree): pass def clear_doc(self, app, env, docname): if docname in env.mpl_plot_image_basenames: del env.mpl_plot_image_basenames[docname] def merge_other(self, app, env, docnames, other): for docname in oth...
_FilenameCollector
python
mlflow__mlflow
mlflow/tracing/utils/search.py
{ "start": 2493, "end": 3010 }
class ____(NamedTuple): """ Represents a parsed field from a string of the form 'span_name.[inputs|outputs]' or 'span_name.[inputs|outputs].field_name'. """ span_name: str field_type: Literal["inputs", "outputs"] field_name: str | None def __str__(self) -> str: return ( ...
_ParsedField
python
sanic-org__sanic
sanic/mixins/listeners.py
{ "start": 307, "end": 863 }
class ____(str, Enum): def _generate_next_value_(name: str, *args) -> str: # type: ignore return name.lower() BEFORE_SERVER_START = "server.init.before" AFTER_SERVER_START = "server.init.after" BEFORE_SERVER_STOP = "server.shutdown.before" AFTER_SERVER_STOP = "server.shutdown.after" MA...
ListenerEvent
python
sanic-org__sanic
sanic/handlers/directory.py
{ "start": 422, "end": 3592 }
class ____: """Serve files from a directory. Args: uri (str): The URI to serve the files at. directory (Path): The directory to serve files from. directory_view (bool): Whether to show a directory listing or not. index (Optional[Union[str, Sequence[str]]]): The index file(s) to ...
DirectoryHandler