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
PyCQA__pylint
tests/functional/i/invalid/invalid_class_object.py
{ "start": 688, "end": 1726 }
class ____: """See https://github.com/pylint-dev/pylint/issues/7467""" def class_defining_function_good(self): self.__class__, myvar = AnotherClass, "myvalue" print(myvar) def class_defining_function_bad(self): self.__class__, myvar = 1, "myvalue" # [invalid-class-object] ...
Pylint7429Good
python
PrefectHQ__prefect
src/prefect/server/schemas/core.py
{ "start": 40541, "end": 41182 }
class ____(ORMBaseModel): """An ORM representation of a worker""" name: str = Field(description="The name of the worker.") work_pool_id: UUID = Field( description="The work pool with which the queue is associated." ) last_heartbeat_time: Optional[datetime.datetime] = Field( None, de...
Worker
python
Pylons__pyramid
tests/test_testing.py
{ "start": 14880, "end": 15030 }
class ____(Test_setUp): def _callFUT(self, *arg, **kw): from pyramid.testing import cleanUp return cleanUp(*arg, **kw)
Test_cleanUp
python
walkccc__LeetCode
solutions/547. Friend Circles/547.py
{ "start": 557, "end": 823 }
class ____: def findCircleNum(self, isConnected: list[list[int]]) -> int: n = len(isConnected) uf = UnionFind(n) for i in range(n): for j in range(i, n): if isConnected[i][j] == 1: uf.unionByRank(i, j) return uf.count
Solution
python
django__django
tests/indexes/tests.py
{ "start": 12691, "end": 14724 }
class ____(TransactionTestCase): available_apps = ["indexes"] def test_no_index_for_foreignkey(self): """ MySQL on InnoDB already creates indexes automatically for foreign keys. (#14180). An index should be created if db_constraint=False (#26171). """ with connection.cur...
SchemaIndexesMySQLTests
python
scipy__scipy
scipy/sparse/tests/test_base.py
{ "start": 6231, "end": 6849 }
class ____: # Custom type to test binary operations on sparse matrices. def __add__(self, mat): return "matrix on the right" def __mul__(self, mat): return "matrix on the right" def __sub__(self, mat): return "matrix on the right" def __radd__(self, mat): return "...
BinopTester
python
pallets__werkzeug
src/werkzeug/routing/map.py
{ "start": 1207, "end": 14732 }
class ____: """The map class stores all the URL rules and some configuration parameters. Some of the configuration values are only stored on the `Map` instance since those affect all rules, others are just defaults and can be overridden for each rule. Note that you have to specify all arguments be...
Map
python
astropy__astropy
astropy/coordinates/representation/spherical.py
{ "start": 15743, "end": 24454 }
class ____(BaseRepresentation): """ Representation of points in 3D spherical coordinates. Parameters ---------- lon, lat : `~astropy.units.Quantity` ['angle'] The longitude and latitude of the point(s), in angular units. The latitude should be between -90 and 90 degrees, and the lon...
SphericalRepresentation
python
fastai__fastai
fastai/vision/core.py
{ "start": 5106, "end": 5312 }
class ____(PILImage): "A BW Pillow `Image` that can show itself and converts to `TensorImageBW`" _show_args,_open_args = {'cmap':'Greys'},{'mode': 'L'} # %% ../../nbs/07_vision.core.ipynb 48
PILImageBW
python
streamlit__streamlit
lib/streamlit/external/langchain/streamlit_callback_handler.py
{ "start": 10021, "end": 15637 }
class ____(BaseCallbackHandler): @gather_metrics("external.langchain.StreamlitCallbackHandler") def __init__( self, parent_container: DeltaGenerator, *, max_thought_containers: int = 4, expand_new_thoughts: bool = False, collapse_completed_thoughts: bool = False, ...
StreamlitCallbackHandler
python
astropy__astropy
astropy/units/decorators.py
{ "start": 3962, "end": 12517 }
class ____: @classmethod def as_decorator(cls, func=None, **kwargs): r""" A decorator for validating the units of arguments to functions. Unit specifications can be provided as keyword arguments to the decorator, or by using function annotation syntax. Arguments to the d...
QuantityInput
python
numba__numba
numba/core/codegen.py
{ "start": 25856, "end": 38039 }
class ____(CodeLibrary): def __init__(self, codegen, name): super().__init__(codegen, name) self._linking_libraries = [] # maintain insertion order self._final_module = ll.parse_assembly( str(self._codegen._create_empty_module(self.name))) self._final_module.name = cgu...
CPUCodeLibrary
python
MongoEngine__mongoengine
mongoengine/queryset/visitor.py
{ "start": 1999, "end": 2505 }
class ____(QNodeVisitor): """Compiles the nodes in a query tree to a PyMongo-compatible query dictionary. """ def __init__(self, document): self.document = document def visit_combination(self, combination): operator = "$and" if combination.operation == combination.OR: ...
QueryCompilerVisitor
python
PyCQA__pylint
doc/data/messages/a/attribute-defined-outside-init/bad.py
{ "start": 0, "end": 109 }
class ____: def register(self): self.is_registered = True # [attribute-defined-outside-init]
Student
python
airbytehq__airbyte
airbyte-integrations/connectors/source-outbrain-amplify/source_outbrain_amplify/source.py
{ "start": 12432, "end": 14674 }
class ____(OutbrainAmplifyStream, HttpSubStream): primary_key = None def __init__(self, authenticator, config, parent: Marketers, **kwargs): super().__init__(parent=parent, **kwargs) self.config = config self._authenticator = authenticator self._session = requests.sessions.Sessi...
BudgetsForMarketers
python
django__django
tests/gis_tests/gis_migrations/test_operations.py
{ "start": 4865, "end": 15587 }
class ____(OperationTestCase): def setUp(self): super().setUp() self.set_up_test_model() def test_add_geom_field(self): """ Test the AddField operation with a geometry-enabled column. """ self.alter_gis_model( migrations.AddField, "Neighborhood", "pat...
OperationTests
python
numba__numba
numba/tests/test_misc_coverage_support.py
{ "start": 211, "end": 2134 }
class ____(TestCase): @TestCase.run_test_in_subprocess(envvars={"NUMBA_JIT_COVERAGE": "1"}) def test_custom_loc_notifier(self): class MyNotify(NotifyLocBase): records = [] def notify(self, loc): self.records.append(("NOTIFY", loc)) def close(self): ...
TestMiscCoverageSupport
python
apache__airflow
providers/apache/tinkerpop/tests/unit/apache/tinkerpop/hooks/test_gremlin.py
{ "start": 1233, "end": 5541 }
class ____: @pytest.mark.parametrize( ("host", "port", "expected_uri"), [ ("host", None, "ws://host:443/gremlin"), ("myhost", 1234, "ws://myhost:1234/gremlin"), ("localhost", 8888, "ws://localhost:8888/gremlin"), ], ) def test_get_uri(self, host, p...
TestGremlinHook
python
rapidsai__cudf
python/cudf_polars/cudf_polars/dsl/ir.py
{ "start": 11796, "end": 32488 }
class ____(IR): """Input from files.""" __slots__ = ( "cloud_options", "include_file_paths", "n_rows", "parquet_options", "paths", "predicate", "reader_options", "row_index", "skip_rows", "typ", "with_columns", ) _n...
Scan
python
airbytehq__airbyte
airbyte-ci/connectors/metadata_service/orchestrator/orchestrator/assets/registry_entry.py
{ "start": 1677, "end": 1796 }
class ____(str, Enum, metaclass=CaseInsensitveKeys): SOURCE = "source" DESTINATION = "destination"
ConnectorTypes
python
pytest-dev__pytest
testing/example_scripts/dataclasses/test_compare_recursive_dataclasses.py
{ "start": 235, "end": 614 }
class ____: g: S h: C2 i: str j: str def test_recursive_dataclasses(): left = C3( S(10, "ten"), C2(C(S(1, "one"), S(2, "two")), S(2, "three")), "equal", "left", ) right = C3( S(20, "xxx"), C2(C(S(1, "one"), S(2, "yyy")), S(3, "three")), ...
C3
python
Textualize__rich
rich/markdown.py
{ "start": 2959, "end": 3480 }
class ____(TextElement): """A Paragraph.""" style_name = "markdown.paragraph" justify: JustifyMethod @classmethod def create(cls, markdown: Markdown, token: Token) -> Paragraph: return cls(justify=markdown.justify or "left") def __init__(self, justify: JustifyMethod) -> None: ...
Paragraph
python
scikit-learn__scikit-learn
sklearn/utils/tests/test_tags.py
{ "start": 390, "end": 456 }
class ____(ClassifierMixin, BaseEstimator): pass
EmptyClassifier
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_operator.py
{ "start": 1718, "end": 25804 }
class ____: def test___all__(self): operator = self.module actual_all = set(operator.__all__) computed_all = set() for name in vars(operator): if name.startswith('__'): continue value = getattr(operator, name) if value.__module__ in...
OperatorTestCase
python
huggingface__transformers
src/transformers/pipelines/deprecated/text2text_generation.py
{ "start": 556, "end": 10295 }
class ____(Pipeline): """ Pipeline for text to text generation using seq2seq models. Unless the model you're using explicitly sets these generation parameters in its configuration files (`generation_config.json`), the following default values will be used: - max_new_tokens: 256 - num_beams: 4 ...
Text2TextGenerationPipeline
python
apache__airflow
providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py
{ "start": 3140, "end": 14767 }
class ____(BaseAuthManager[KeycloakAuthManagerUser]): """ Keycloak auth manager. Leverages Keycloak to perform authentication and authorization in Airflow. """ def deserialize_user(self, token: dict[str, Any]) -> KeycloakAuthManagerUser: return KeycloakAuthManagerUser( user_id=...
KeycloakAuthManager
python
PrefectHQ__prefect
tests/server/models/test_workers.py
{ "start": 7444, "end": 8056 }
class ____: async def test_count_work_pool( self, session: AsyncSession, work_pool: schemas.core.WorkPool ): result = await models.workers.count_work_pools( session=session, ) assert result == 1 random_name = "not-my-work-pool" assert random_name != w...
TestCountWorkPools
python
pennersr__django-allauth
tests/apps/socialaccount/providers/digitalocean/tests.py
{ "start": 252, "end": 1344 }
class ____(OAuth2TestsMixin, TestCase): provider_id = DigitalOceanProvider.id def get_mocked_response(self): return MockedResponse( HTTPStatus.OK, """ { "account": { "droplet_limit": 25, "floating_ip_limit": 5, "email": "samm...
DigitalOceanTests
python
huggingface__transformers
tests/models/llava_onevision/test_modeling_llava_onevision.py
{ "start": 6039, "end": 10530 }
class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): """ Model tester for `LlavaOnevisionForConditionalGeneration`. """ all_model_classes = ( ( LlavaOnevisionModel, LlavaOnevisionForConditionalGeneration, ) if is_torch_available() ...
LlavaOnevisionForConditionalGenerationModelTest
python
apache__airflow
providers/openlineage/src/airflow/providers/openlineage/plugins/facets.py
{ "start": 3825, "end": 4116 }
class ____(RedactMixin): """ Describes an unknown operator. This specifies the (class) name of the operator and its properties. """ name: str properties: dict[str, object] type: str = "operator" _skip_redact = ["name", "type"] @define
UnknownOperatorInstance
python
Pylons__pyramid
docs/tutorials/wiki/src/tests/tests/test_views.py
{ "start": 1263, "end": 2219 }
class ____: def _callFUT(self, context, request): from tutorial.views.default import add_page return add_page(context, request) def test_it_notsubmitted(self): context = testing.DummyResource() request = testing.DummyRequest() request.subpath = ['AnotherPage'] in...
Test_add_page
python
pytest-dev__pytest
src/_pytest/reports.py
{ "start": 9330, "end": 14951 }
class ____(BaseReport): """Basic test report object (also used for setup and teardown calls if they fail). Reports can contain arbitrary extra attributes. """ __test__ = False # Defined by skipping plugin. # xfail reason if xfailed, otherwise not defined. Use hasattr to distinguish. w...
TestReport
python
doocs__leetcode
solution/3200-3299/3264.Final Array State After K Multiplication Operations I/Solution.py
{ "start": 0, "end": 321 }
class ____: def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]: pq = [(x, i) for i, x in enumerate(nums)] heapify(pq) for _ in range(k): _, i = heappop(pq) nums[i] *= multiplier heappush(pq, (nums[i], i)) return nums
Solution
python
jazzband__django-oauth-toolkit
oauth2_provider/migrations/0009_add_hash_client_secret.py
{ "start": 92, "end": 416 }
class ____(migrations.Migration): dependencies = [ ('oauth2_provider', '0008_alter_accesstoken_token'), ] operations = [ migrations.AddField( model_name='application', name='hash_client_secret', field=models.BooleanField(default=True), ), ]
Migration
python
Textualize__rich
examples/rainbow.py
{ "start": 166, "end": 441 }
class ____(Highlighter): def highlight(self, text): for index in range(len(text)): text.stylize(f"color({randint(16, 255)})", index, index + 1) rainbow = RainbowHighlighter() print(rainbow("I must not fear. Fear is the mind-killer."))
RainbowHighlighter
python
celery__celery
t/unit/backends/test_database.py
{ "start": 744, "end": 1233 }
class ____: def test_context(self): session = Mock(name='session') with session_cleanup(session): pass session.close.assert_called_with() def test_context_raises(self): session = Mock(name='session') with pytest.raises(KeyError): with session_cle...
test_session_cleanup
python
dagster-io__dagster
scripts/run-pyright.py
{ "start": 3726, "end": 3866 }
class ____(TypedDict): filesAnalyzed: int errorCount: int warningCount: int informationCount: int timeInSec: float
Summary
python
pytorch__pytorch
test/distributed/_composable/test_composability/test_2d_composability.py
{ "start": 2523, "end": 3067 }
class ____(nn.Module): def __init__(self): super().__init__() torch.manual_seed(0) self.net1 = nn.Linear(5, 10) self.relu = nn.ReLU() self.net2 = nn.Linear(10, 15) self.net3 = nn.Linear(15, 30) self.net4 = nn.Linear(30, 5) def forward(self, x): x ...
SimpleModelUneven
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/extra/codemods.py
{ "start": 3144, "end": 4196 }
class ____(VisitorBasedCodemodCommand): """Fix a deprecated min_magnitude=None argument for complex numbers:: st.complex_numbers(min_magnitude=None) -> st.complex_numbers(min_magnitude=0) Note that this should be run *after* ``HypothesisFixPositionalKeywonlyArgs``, in order to handle ``st.complex_...
HypothesisFixComplexMinMagnitude
python
Pylons__pyramid
tests/test_url.py
{ "start": 42651, "end": 43489 }
class ____(unittest.TestCase): def _callFUT(self, route_name, request, *elements, **kw): from pyramid.url import route_path return route_path(route_name, request, *elements, **kw) def _makeRequest(self): class Request: def route_path(self, route_name, *elements, **kw): ...
Test_route_path
python
PyCQA__pylint
pylint/checkers/classes/class_checker.py
{ "start": 2071, "end": 2227 }
class ____(NamedTuple): args: list[str | None] kws: dict[str | None, str | None] starred_args: list[str] starred_kws: list[str]
_CallSignature
python
pennersr__django-allauth
allauth/socialaccount/providers/openid/utils.py
{ "start": 1230, "end": 1444 }
class ____: PERSON_NAME = "http://openid.net/schema/namePerson" PERSON_FIRST_NAME = "http://openid.net/schema/namePerson/first" PERSON_LAST_NAME = "http://openid.net/schema/namePerson/last"
OldAXAttribute
python
anthropics__anthropic-sdk-python
src/anthropic/lib/streaming/_beta_messages.py
{ "start": 5169, "end": 6223 }
class ____(Generic[ResponseFormatT]): """Wrapper over MessageStream that is returned by `.stream()`. ```py with client.beta.messages.stream(...) as stream: for chunk in stream: ... ``` """ def __init__( self, api_request: Callable[[], Stream[BetaRawMessageSt...
BetaMessageStreamManager
python
django__django
tests/db_functions/text/test_sha1.py
{ "start": 226, "end": 1640 }
class ____(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create( [ Author(alias="John Smith"), Author(alias="Jordan Élena"), Author(alias="皇帝"), Author(alias=""), Author(alias=None), ...
SHA1Tests
python
fastapi__sqlmodel
docs_src/tutorial/relationship_attributes/cascade_delete_relationships/tutorial001.py
{ "start": 359, "end": 3401 }
class ____(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) team_id: Optional[int] = Field( default=None, foreign_key="team.id", ondelete="CASCADE" ) t...
Hero
python
airbytehq__airbyte
airbyte-ci/connectors/metadata_service/lib/tests/test_registry.py
{ "start": 7285, "end": 12173 }
class ____: """Tests for _build_connector_registry function.""" @pytest.mark.parametrize( "entry_dicts,expected_sources_count,expected_destinations_count,description", [ ( [ { "sourceDefinitionId": "550e8400-e29b-41d4-a716-...
TestBuildConnectorRegistry
python
apache__airflow
providers/ydb/tests/unit/ydb/hooks/test_ydb.py
{ "start": 1332, "end": 1419 }
class ____: def __init__(self, driver): self._driver = driver
FakeSessionPool
python
pytorch__pytorch
torch/testing/_internal/autograd_function_db.py
{ "start": 14528, "end": 19613 }
class ____(torch.autograd.Function): @staticmethod def forward(x, idx=(2,)): return x[idx] @staticmethod def setup_context(ctx, inputs, output): x, idx = inputs ctx.x_shape = x.shape ctx.idx = idx @staticmethod def backward(ctx, grad_output): result = gr...
ForwardHasDefaultArgs
python
kamyu104__LeetCode-Solutions
Python/find-the-integer-added-to-array-ii.py
{ "start": 1582, "end": 2099 }
class ____(object): def minimumAddedInteger(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: int """ nums1.sort() nums2.sort() for i in xrange(3): d = nums2[-1]-nums1[~i] cnt = 0 for j i...
Solution3
python
django__django
tests/template_tests/filter_tests/test_urlize.py
{ "start": 4021, "end": 19894 }
class ____(SimpleTestCase): def test_urls(self): self.assertEqual( urlize("http://google.com"), '<a href="http://google.com" rel="nofollow">http://google.com</a>', ) self.assertEqual( urlize("http://google.com/"), '<a href="http://google.com/" ...
FunctionTests
python
spack__spack
var/spack/test_repos/spack_repo/requirements_test/packages/u/package.py
{ "start": 216, "end": 307 }
class ____(Package): version("1.1") version("1.0") depends_on("c", type="build")
U
python
tensorflow__tensorflow
third_party/xla/xla/python/xla_client.py
{ "start": 14507, "end": 14920 }
class ____: """Python representation of a xla.ScatterDimensionNumbers protobuf.""" __slots__ = ( 'update_window_dims', 'inserted_window_dims', 'scatter_dims_to_operand_dims', 'index_vector_dim', ) def __init__(self): self.update_window_dims = [] self.inserted_window_dims = [] ...
ScatterDimensionNumbers
python
mlflow__mlflow
mlflow/store/tracking/databricks_rest_store.py
{ "start": 2433, "end": 30451 }
class ____(RestStore): """ Client for a databricks tracking server accessed via REST API calls. This is only used for Databricks-specific tracing APIs, all other APIs including runs, experiments, models etc. should be implemented in the RestStore. Args get_host_creds: Method to be invoked p...
DatabricksTracingRestStore
python
PrefectHQ__prefect
src/prefect/utilities/annotations.py
{ "start": 3189, "end": 4396 }
class ____(BaseAnnotation[T]): """ Wrapper for parameters in deployments. Indicates that this parameter should be frozen in the UI and not editable when creating flow runs from this deployment. Example: ```python @flow def my_flow(customer_id: str): # flow logic deployment...
freeze
python
weaviate__weaviate-python-client
weaviate/collections/classes/config_vectorizers.py
{ "start": 16881, "end": 17358 }
class ____(_Multi2VecBase): vectorizer: Union[Vectorizers, _EnumLikeStr] = Field( default=Vectorizers.MULTI2VEC_JINAAI, frozen=True, exclude=True ) baseURL: Optional[AnyHttpUrl] model: Optional[str] dimensions: Optional[int] def _to_dict(self) -> Dict[str, Any]: ret_dict = super...
_Multi2VecJinaConfig
python
ipython__ipython
IPython/core/completer.py
{ "start": 28633, "end": 30548 }
class ____: """An object to split an input line in a manner similar to readline. By having our own implementation, we can expose readline-like completion in a uniform manner to all frontends. This object only needs to be given the line of text to be split and the cursor position on said line, and it ...
CompletionSplitter
python
wandb__wandb
wandb/sdk/artifacts/_generated/update_artifact_sequence_type.py
{ "start": 259, "end": 361 }
class ____(GQLResult): result: Optional[UpdateArtifactSequenceTypeResult]
UpdateArtifactSequenceType
python
tiangolo__fastapi
docs_src/graphql/tutorial001.py
{ "start": 110, "end": 168 }
class ____: name: str age: int @strawberry.type
User
python
optuna__optuna
tests/test_deprecated.py
{ "start": 108, "end": 6676 }
class ____: def __init__(self, a: Any, b: Any, c: Any) -> None: pass def _method(self) -> None: """summary detail """ pass def _method_expected(self) -> None: """summary detail .. warning:: Deprecated in v1.1.0. This feature wi...
_Sample
python
catalyst-team__catalyst
catalyst/data/sampler.py
{ "start": 352, "end": 3556 }
class ____(Sampler): """Allows you to create stratified sample on unbalanced classes. Args: labels: list of class label for each elem in the dataset mode: Strategy to balance classes. Must be one of [downsampling, upsampling] Python API examples: .. code-block:: python ...
BalanceClassSampler
python
getsentry__sentry
src/sentry/notifications/helpers.py
{ "start": 2844, "end": 6382 }
class ____(TypedDict, total=False): disabled: bool reason: str def get_subscription_from_attributes( attrs: Mapping[str, Any], ) -> tuple[bool, SubscriptionDetails | None]: subscription_details: SubscriptionDetails | None = None is_disabled, is_subscribed, subscription = attrs["subscription"] ...
SubscriptionDetails
python
facebookresearch__faiss
tests/test_ivflib.py
{ "start": 1730, "end": 2296 }
class ____(unittest.TestCase): def test_sequential_scan(self): d = 20 index = faiss.index_factory(d, 'IVF100,SQ8') rs = np.random.RandomState(123) xt = rs.rand(5000, d).astype('float32') xb = rs.rand(10000, d).astype('float32') index.train(xt) index.add(xb) ...
TestSequentialScan
python
crytic__slither
slither/core/declarations/contract.py
{ "start": 1668, "end": 62849 }
class ____(SourceMapping): # pylint: disable=too-many-public-methods """ Contract class """ def __init__(self, compilation_unit: "SlitherCompilationUnit", scope: "FileScope") -> None: super().__init__() self._name: Optional[str] = None self._id: Optional[int] = None se...
Contract
python
getsentry__sentry
tests/sentry/monitors/consumers/test_clock_tick_consumer.py
{ "start": 4363, "end": 7984 }
class ____(TestCase): @thread_leaks.thread_leak_allowlist(reason="monitors", issue=97032) @override_settings(SENTRY_EVENTSTREAM="sentry.eventstream.kafka.KafkaEventStream") def test_end_to_end(self) -> None: ts = timezone.now().replace(second=0, microsecond=0) broker: LocalBroker[KafkaPaylo...
MonitorsClockTickEndToEndTest
python
ray-project__ray
doc/source/serve/doc_code/quickstart_composed.py
{ "start": 517, "end": 1434 }
class ____: def __init__( self, adder1: DeploymentHandle, adder2: DeploymentHandle, combiner: DeploymentHandle, ): self._adder1 = adder1 self._adder2 = adder2 self._combiner = combiner async def __call__(self, request: starlette.requests.Request) -> D...
Ingress
python
matplotlib__matplotlib
lib/matplotlib/font_manager.py
{ "start": 32971, "end": 35056 }
class ____(json.JSONEncoder): def default(self, o): if isinstance(o, FontManager): return dict(o.__dict__, __class__='FontManager') elif isinstance(o, FontEntry): d = dict(o.__dict__, __class__='FontEntry') try: # Cache paths of fonts shipped with ...
_JSONEncoder
python
kamyu104__LeetCode-Solutions
Python/minimum-cost-path-with-alternating-directions-ii.py
{ "start": 690, "end": 1297 }
class ____(object): def minCost(self, m, n, waitCost): """ :type m: int :type n: int :type waitCost: List[List[int]] :rtype: int """ waitCost[0][0] = waitCost[m-1][n-1] = 0 dp = [0]*n for i in xrange(m): for j in xrange(n): ...
Solution2
python
django__django
tests/select_related_onetoone/models.py
{ "start": 139, "end": 315 }
class ____(models.Model): user = models.OneToOneField(User, models.CASCADE) city = models.CharField(max_length=100) state = models.CharField(max_length=2)
UserProfile
python
rapidsai__cudf
python/cudf_polars/cudf_polars/dsl/expressions/rolling.py
{ "start": 1420, "end": 2777 }
class ____(UnaryOp): pass def to_request( value: expr.Expr, orderby: Column, df: DataFrame ) -> plc.rolling.RollingRequest: """ Produce a rolling request for evaluation with pylibcudf. Parameters ---------- value The expression to perform the rolling aggregation on. orderby ...
CumSumOp
python
great-expectations__great_expectations
great_expectations/data_context/store/gx_cloud_store_backend.py
{ "start": 986, "end": 1113 }
class ____(TypedDict): code: Optional[str] detail: Optional[str] source: Union[str, Dict[str, str], None]
ErrorDetail
python
realpython__materials
inheritance-and-composition/inheritance/productivity.py
{ "start": 306, "end": 409 }
class ____: def work(self, hours): return f"screams and yells for {hours} hours."
ManagerRole
python
coleifer__peewee
peewee.py
{ "start": 260995, "end": 262084 }
class ____(_ModelWriteQueryHelper, Insert): default_row_type = ROW.TUPLE def __init__(self, *args, **kwargs): super(ModelInsert, self).__init__(*args, **kwargs) if self._returning is None and self.model._meta.database is not None: if self.model._meta.database.returning_clause: ...
ModelInsert
python
celery__celery
t/unit/tasks/test_canvas.py
{ "start": 1169, "end": 2691 }
class ____: def setup_method(self): @self.app.task(shared=False) def add(x, y): return x + y self.add = add @self.app.task(shared=False) def mul(x, y): return x * y self.mul = mul @self.app.task(shared=False) def div(x, y):...
CanvasCase
python
huggingface__transformers
tests/models/switch_transformers/test_modeling_switch_transformers.py
{ "start": 1660, "end": 21387 }
class ____: def __init__( self, parent, vocab_size=99, batch_size=13, encoder_seq_length=7, decoder_seq_length=9, # For common tests is_training=True, use_attention_mask=True, use_labels=True, hidden_size=32, num_hidden_...
SwitchTransformersModelTester
python
ray-project__ray
ci/ray_ci/bisect/macos_validator.py
{ "start": 212, "end": 762 }
class ____(Validator): def run(self, test: Test, revision: str) -> bool: env = os.environ.copy() # We need to unset PYTHONPATH to avoid conflicts with the Python from the # Bazel runfiles. env.update({"RAYCI_BISECT_RUN": "1", "PYTHONPATH": ""}) return ( subprocess...
MacOSValidator
python
getsentry__sentry
tests/sentry/workflow_engine/models/test_data_condition.py
{ "start": 388, "end": 452 }
class ____(IntEnum): FOO = 1 BAR = 2
MockDataConditionEnum
python
plotly__plotly.py
plotly/graph_objs/table/cells/_font.py
{ "start": 233, "end": 17063 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "table.cells" _path_str = "table.cells.font" _valid_props = { "color", "colorsrc", "family", "familysrc", "lineposition", "linepositionsrc", "shadow", "shadowsrc", "size", ...
Font
python
doocs__leetcode
solution/3300-3399/3398.Smallest Substring With Identical Characters I/Solution.py
{ "start": 0, "end": 631 }
class ____: def minLength(self, s: str, numOps: int) -> int: def check(m: int) -> bool: cnt = 0 if m == 1: t = "01" cnt = sum(c == t[i & 1] for i, c in enumerate(s)) cnt = min(cnt, n - cnt) else: k = 0 ...
Solution
python
pytorch__pytorch
torch/_logging/_internal.py
{ "start": 1810, "end": 5335 }
class ____: # shorthand name to log qualified name # Note: this only contains loggers registered # from register_log # e.g. "dynamo" -> "torch._dynamo" log_alias_to_log_qnames: dict[str, list[str]] = field(default_factory=dict) # artifact logger qualified names, # this is populated lazily, ...
LogRegistry
python
django-extensions__django-extensions
django_extensions/mongodb/fields/__init__.py
{ "start": 6142, "end": 6522 }
class ____(DateTimeField): """ CreationDateTimeField By default, sets editable=False, blank=True, default=datetime.now """ def __init__(self, *args, **kwargs): kwargs.setdefault("default", datetime.datetime.now) DateTimeField.__init__(self, *args, **kwargs) def get_internal_ty...
CreationDateTimeField
python
pydantic__pydantic
pydantic/networks.py
{ "start": 25740, "end": 25961 }
class ____(AnyUrl): """A type that will accept any AMQP DSN. * User info required * TLD not required * Host not required """ _constraints = UrlConstraints(allowed_schemes=['amqp', 'amqps'])
AmqpDsn
python
sqlalchemy__sqlalchemy
test/engine/test_deprecations.py
{ "start": 15172, "end": 15728 }
class ____(fixtures.TestBase): __backend__ = True @testing.combinations(True, False, None, argnames="implicit_returning") def test_implicit_returning_engine_parameter(self, implicit_returning): if implicit_returning is None: engines.testing_engine() else: with assert...
ImplicitReturningFlagTest
python
mlflow__mlflow
mlflow/pyfunc/model.py
{ "start": 61469, "end": 66208 }
class ____(PythonModel): """ A PythonModel wrapper for invoking an MLflow Deployments endpoint. This class is particularly used for running evaluation against an MLflow Deployments endpoint. """ def __init__(self, endpoint, params): self.endpoint = endpoint self.params = params ...
ModelFromDeploymentEndpoint
python
getsentry__sentry
src/sentry/hybridcloud/rpc/sig.py
{ "start": 819, "end": 6729 }
class ____: """Represent a function's parameters and return type for serialization.""" def __init__(self, base_function: Callable[..., Any], is_instance_method: bool = False) -> None: super().__init__() self.base_function = base_function self.is_instance_method = is_instance_method ...
SerializableFunctionSignature
python
django__django
tests/multiple_database/models.py
{ "start": 1823, "end": 1994 }
class ____(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey(Person, models.CASCADE) class Meta: ordering = ("name",)
Pet
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/base.py
{ "start": 11064, "end": 12815 }
class ____(MutableMapping[str, Any]): """A dictionary view of dialect-level arguments in the form <dialectname>_<argument_name>. """ __slots__ = ("obj",) def __init__(self, obj: DialectKWArgs) -> None: self.obj = obj def _key(self, key: str) -> Tuple[str, str]: try: ...
_DialectArgView
python
pytorch__pytorch
torch/_inductor/comm_analysis.py
{ "start": 578, "end": 3325 }
class ____(IntEnum): VOLTA = 0 AMPERE = 1 HOPPER = 2 @functools.lru_cache def get_gpu_type() -> NVIDIA_GPU_TYPE: gpu_info = torch.utils.collect_env.get_gpu_info(torch.utils.collect_env.run) or "" if "V100" in gpu_info: return NVIDIA_GPU_TYPE.VOLTA elif "A100" in gpu_info: retur...
NVIDIA_GPU_TYPE
python
google__jax
jax/_src/interpreters/mlir.py
{ "start": 26892, "end": 31674 }
class ____: """Module-wide context information for MLIR lowering.""" context: ir.Context module: ir.Module ip: ir.InsertionPoint symbol_table: ir.SymbolTable # The lowering platforms for the module. Can be more than one only when # exporting. platforms: Sequence[str] # See ModuleContext.get_backend() ...
ModuleContext
python
scipy__scipy
scipy/sparse/linalg/_eigen/tests/test_svds.py
{ "start": 34153, "end": 34449 }
class ____: @pytest.mark.parametrize("solver", ['ekki', object]) def test_svds_input_validation_solver(self, solver): message = "solver must be one of" with pytest.raises(ValueError, match=message): svds(np.ones((3, 4)), k=2, solver=solver, rng=0)
Test_SVDS_once
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/metaclass3.py
{ "start": 528, "end": 554 }
class ____(type): ...
Meta10
python
Textualize__textual
src/textual/getters.py
{ "start": 1801, "end": 4518 }
class ____(Generic[QueryType]): """Create a query one property. A query one property calls [Widget.query_one][textual.dom.DOMNode.query_one] when accessed, and returns a widget. If the widget doesn't exist, then the property will raise the same exceptions as `Widget.query_one`. Example: ```py...
query_one
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/sqltypes.py
{ "start": 4802, "end": 5482 }
class ____(TypeEngineMixin): """A mixin that marks a type as supporting indexing operations, such as array or JSON structures. """ class Comparator(TypeEngine.Comparator[_T]): __slots__ = () def _setup_getitem(self, index): raise NotImplementedError() def __getite...
Indexable
python
airbytehq__airbyte
airbyte-integrations/connectors/source-iterable/source_iterable/streams.py
{ "start": 16178, "end": 16271 }
class ____(IterableExportStreamAdjustableRange): data_field = "emailSendSkip"
EmailSendSkip
python
matplotlib__matplotlib
lib/matplotlib/transforms.py
{ "start": 37747, "end": 40080 }
class ____(BboxBase): """ A `Bbox` that is automatically transformed by a given transform. When either the child bounding box or transform changes, the bounds of this bbox will update accordingly. """ def __init__(self, bbox, transform, **kwargs): """ Parameters -------...
TransformedBbox
python
HypothesisWorks__hypothesis
hypothesis-python/tests/django/toystore/models.py
{ "start": 4070, "end": 4311 }
class ____(models.IntegerField): def pre_save(self, model_instance, add): value = getattr(model_instance, self.attname) value += 1 setattr(model_instance, self.attname, value) return value
SelfModifyingField
python
pytorch__pytorch
torch/_inductor/fuzzer.py
{ "start": 14667, "end": 19862 }
class ____: """ The mapping of the combo strings to the result status after running the config fuzzer. """ _vals: dict[ComboType, Status] def __repr__(self) -> str: return f"ResultType[{self._vals}]" def __init__(self) -> None: self._vals = {} def __len__(self) -> int: ...
ResultType
python
django__django
tests/check_framework/test_files.py
{ "start": 176, "end": 1173 }
class ____(SimpleTestCase): def test_file_upload_temp_dir(self): tests = [ None, "", Path.cwd(), str(Path.cwd()), ] for setting in tests: with self.subTest(setting), self.settings(FILE_UPLOAD_TEMP_DIR=setting): self....
FilesCheckTests
python
Netflix__metaflow
test/unit/inheritance/flows/mutator_with_base_config_base.py
{ "start": 2271, "end": 2535 }
class ____(BaseA): """ Middle class with mutator that uses config from BaseA. The mutator reads mutator_config from BaseA and injects parameters accordingly. """ middle_param = Parameter("middle_param", help="Middle parameter", default=100)
BaseB
python
django__django
django/contrib/gis/db/models/functions.py
{ "start": 20718, "end": 21085 }
class ____(Scale): def as_sqlite(self, compiler, connection, **extra_context): clone = self.copy() if len(self.source_expressions) < 4: # Always provide the z parameter for ST_Translate clone.source_expressions.append(Value(0)) return super(Translate, clone).as_sqlite...
Translate
python
google__flatbuffers
python/flatbuffers/builder.py
{ "start": 1240, "end": 1382 }
class ____(RuntimeError): """Error caused by using a Builder to write Object data when not inside an Object. """ pass
IsNotNestedError