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
kamyu104__LeetCode-Solutions
Python/serialize-and-deserialize-binary-tree.py
{ "start": 1474, "end": 2569 }
class ____(object): def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ def gen_preorder(node): if not node: yield '#' else: yield str(node.val) ...
Codec2
python
PrefectHQ__prefect
tests/server/models/test_deployments.py
{ "start": 27539, "end": 49016 }
class ____: async def test_schedule_runs_inserts_in_db(self, deployment, session): scheduled_runs = await models.deployments.schedule_runs( session, deployment_id=deployment.id ) assert len(scheduled_runs) == PREFECT_API_SERVICES_SCHEDULER_MIN_RUNS.value() query_result = ...
TestScheduledRuns
python
PyCQA__pylint
doc/data/messages/i/implicit-flag-alias/good.py
{ "start": 27, "end": 102 }
class ____(IntFlag): READ = 1 WRITE = 2 EXECUTE = 4
FilePermissions
python
huggingface__transformers
tests/repo_utils/test_check_docstrings.py
{ "start": 914, "end": 4978 }
class ____(unittest.TestCase): def test_replace_default_in_arg_description(self): # Standard docstring with default. desc_with_default = "`float`, *optional*, defaults to 2.0" self.assertEqual( replace_default_in_arg_description(desc_with_default, 2.0), "`float`, *optional*, defa...
CheckDostringsTested
python
pytorch__pytorch
torch/_inductor/ir.py
{ "start": 124518, "end": 134374 }
class ____(OutputSpec): """ Layout base class Carries tensor meta-information including offset and whether it is pinned. """ def __init__( self, device: torch.device, dtype: torch.dtype, size: Sequence[Expr], stride: Optional[Sequence[Expr]] = None, ...
Layout
python
pytest-dev__pytest
testing/test_terminal.py
{ "start": 15929, "end": 22175 }
class ____: def test_collectonly_basic(self, pytester: Pytester) -> None: pytester.makepyfile( """ def test_func(): pass """ ) result = pytester.runpytest("--collect-only") result.stdout.fnmatch_lines( [ "<Di...
TestCollectonly
python
doocs__leetcode
solution/0800-0899/0846.Hand of Straights/Solution2.py
{ "start": 0, "end": 498 }
class ____: def isNStraightHand(self, hand: List[int], groupSize: int) -> bool: if len(hand) % groupSize: return False cnt = Counter(hand) sd = SortedDict(cnt) while sd: x = next(iter(sd)) for y in range(x, x + groupSize): if y not ...
Solution
python
airbytehq__airbyte
airbyte-ci/connectors/metadata_service/orchestrator/orchestrator/models/metadata.py
{ "start": 1443, "end": 1530 }
class ____(PydanticDictMixin, ConnectorMetadataDefinitionV0): pass
MetadataDefinition
python
django__django
tests/admin_views/tests.py
{ "start": 308491, "end": 309585 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) def setUp(self): self.client.force_login(self.superuser) def test_limit_choices_to_as_callable(...
LimitChoicesToInAdminTest
python
huggingface__transformers
tests/models/auto/test_processor_auto.py
{ "start": 2623, "end": 20998 }
class ____(unittest.TestCase): vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"] def setUp(self): transformers.dynamic_module_utils.TIME_OUT_REMOTE_CODE = 0 def test_processor_from_model_shortcut(self): processor = AutoProcessor.from_pretrained("facebook/wav2vec2...
AutoFeatureExtractorTest
python
PrefectHQ__prefect
src/prefect/logging/handlers.py
{ "start": 11746, "end": 13547 }
class ____(StreamHandler): def __init__( self, stream: TextIO | None = None, highlighter: type[Highlighter] = PrefectConsoleHighlighter, styles: dict[str, str] | None = None, level: int | str = logging.NOTSET, ): """ The default console handler for Prefect...
PrefectConsoleHandler
python
getsentry__sentry
tests/sentry/utils/test_exceptions.py
{ "start": 15625, "end": 16953 }
class ____: def test_basic_functionality_minimal_mocking(self) -> None: with patch("sentry_sdk.new_scope") as mock_scope: mock_scope_instance = Mock() mock_scope.return_value.__enter__ = Mock(return_value=mock_scope_instance) mock_scope.return_value.__exit__ = Mock(return...
TestSetSentryExceptionLevels
python
google__pytype
pytype/tools/analyze_project/config_test.py
{ "start": 3008, "end": 3813 }
class ____(TestBase): """Test Config.""" def test_populate_from(self): conf = config.Config() self._validate_empty_contents(conf) conf.populate_from( types.SimpleNamespace(**{k: 42 for k in config.ITEMS})) for k in config.ITEMS: self.assertEqual(getattr(conf, k), 42) def test_popul...
TestConfig
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/hooks/kinesis_analytics.py
{ "start": 891, "end": 2287 }
class ____(AwsBaseHook): """ Interact with Amazon Kinesis Analytics V2. Provide thin wrapper around :external+boto3:py:class:`boto3.client("kinesisanalyticsv2") <KinesisAnalyticsV2.Client>`. Additional arguments (such as ``aws_conn_id``) may be specified and are passed down to the underlying AwsBa...
KinesisAnalyticsV2Hook
python
numpy__numpy
numpy/distutils/fcompiler/intel.py
{ "start": 6100, "end": 6570 }
class ____(IntelVisualFCompiler): compiler_type = 'intelvem' description = 'Intel Visual Fortran Compiler for 64-bit apps' version_match = simple_version_match(start=r'Intel\(R\).*?64,') def get_flags_arch(self): return [] if __name__ == '__main__': from distutils import log log.set_...
IntelEM64VisualFCompiler
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 113632, "end": 118867 }
class ____(Request): """ Update existing artifacts (search by key/mode) and add new ones :param task: Task ID :type task: str :param artifacts: Artifacts to add or update :type artifacts: Sequence[Artifact] :param force: If set to True then both new and running task artifacts can be ...
AddOrUpdateArtifactsRequest
python
tensorflow__tensorflow
tensorflow/lite/python/lite.py
{ "start": 131716, "end": 133571 }
class ____: """Convert a TensorFlow model into `output_format`. This class has been deprecated. Please use `lite.TFLiteConverter` instead. """ @classmethod @_deprecation.deprecated( None, "Use `lite.TFLiteConverter.from_session` instead." ) def from_session(cls, sess, input_tensors, output_tensors...
TocoConverter
python
pydantic__pydantic
tests/mypy/modules/root_models.py
{ "start": 481, "end": 526 }
class ____(RootModel[T | None]): pass
Maybe
python
django-compressor__django-compressor
compressor/filters/base.py
{ "start": 1816, "end": 3720 }
class ____(FilterBase): """ A filter which takes function path in `callback` attribute, imports it and uses that function to filter output string:: class MyFilter(CallbackOutputFilter): callback = 'path.to.my.callback' Callback should be a function which takes a string as first arg...
CallbackOutputFilter
python
pennersr__django-allauth
allauth/socialaccount/providers/dataporten/views.py
{ "start": 248, "end": 2576 }
class ____(OAuth2Adapter): provider_id = "dataporten" access_token_url = "https://auth.dataporten.no/oauth/token" # nosec authorize_url = "https://auth.dataporten.no/oauth/authorization" profile_url = "https://auth.dataporten.no/userinfo" groups_url = "https://groups-api.dataporten.no/groups/" ...
DataportenOAuth2Adapter
python
rapidsai__cudf
python/cudf_polars/cudf_polars/experimental/io.py
{ "start": 18596, "end": 21831 }
class ____: """ Parquet metadata container. Parameters ---------- paths Parquet-dataset paths. max_footer_samples Maximum number of file footers to sample metadata from. """ __slots__ = ( "column_names", "max_footer_samples", "mean_size_per_file"...
ParquetMetadata
python
tensorflow__tensorflow
tensorflow/python/ops/summary_ops_v2.py
{ "start": 9227, "end": 11931 }
class ____(metaclass=abc.ABCMeta): """Interface representing a stateful summary writer object.""" def set_as_default(self, step=None): """Enables this summary writer for the current thread. For convenience, if `step` is not None, this function also sets a default value for the `step` parameter used in...
SummaryWriter
python
python__mypy
test-data/unit/plugins/magic_method.py
{ "start": 492, "end": 851 }
class ____(Plugin): def get_method_hook(self, fullname: str) -> Optional[Callable[[MethodContext], Type]]: if fullname == 'builtins.int.__add__': return type_add if fullname == 'builtins.int.__radd__': return type_radd return None def plugin(version: str) -> type[Te...
TestPlugin
python
kamyu104__LeetCode-Solutions
Python/walking-robot-simulation.py
{ "start": 33, "end": 815 }
class ____(object): def robotSim(self, commands, obstacles): """ :type commands: List[int] :type obstacles: List[List[int]] :rtype: int """ directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] x, y, i = 0, 0, 0 lookup = set(map(tuple, obstacles)) re...
Solution
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-dashscope/tests/test_dashscope.py
{ "start": 408, "end": 1339 }
class ____: def __init__(self, data: dict): self.status_code = data["status_code"] self.output = SimpleNamespace(**data["output"]) def __repr__(self) -> str: return f"<FakeDashscopeResponse status_code={self.status_code}>" @pytest.fixture() def dashscope_llm(): return DashScope(ap...
FakeDashscopeResponse
python
pandas-dev__pandas
pandas/tests/extension/test_arrow.py
{ "start": 7810, "end": 40579 }
class ____(base.ExtensionTests): def _construct_for_combine_add(self, left, right): dtype = left.dtype # in a couple cases, addition is not dtype-preserving if dtype == "bool[pyarrow]": dtype = pandas_dtype("int64[pyarrow]") elif dtype == "int8[pyarrow]" and isinstance(r...
TestArrowArray
python
ansible__ansible
lib/ansible/modules/hostname.py
{ "start": 26052, "end": 26173 }
class ____(Hostname): platform = 'FreeBSD' distribution = None strategy_class = FreeBSDStrategy
FreeBSDHostname
python
davidhalter__parso
test/test_parser_tree.py
{ "start": 204, "end": 8273 }
class ____: FIXTURES = [ ('def my_function(x, y, z) -> str:\n return x + y * z\n', { 'name': 'my_function', 'call_sig': 'my_function(x, y, z)', 'params': ['x', 'y', 'z'], 'annotation': "str", }), ('lambda x, y, z: x + y * z\n', { ...
TestsFunctionAndLambdaParsing
python
realpython__materials
python-selenium/src/bandcamp/web/locators.py
{ "start": 251, "end": 370 }
class ____: ITEM = (By.CLASS_NAME, "results-grid-item") PAGINATION_BUTTON = (By.ID, "view-more")
TrackListLocator
python
dagster-io__dagster
python_modules/dagster/dagster/components/utils/defs_state.py
{ "start": 2033, "end": 2617 }
class ____: key: str management_type: DefsStateManagementType refresh_if_dev: bool @classmethod def from_args(cls, args: DefsStateConfigArgs, default_key: str) -> "DefsStateConfig": return cls( key=args.key or default_key, management_type=args.management_type, ...
DefsStateConfig
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py
{ "start": 48943, "end": 51404 }
class ____: @mock.patch(VERTEX_AI_PATH.format("custom_job.CustomJobHook")) def test_execute(self, mock_hook): op = DeleteCustomTrainingJobOperator( task_id=TASK_ID, training_pipeline_id=TRAINING_PIPELINE_ID, custom_job_id=CUSTOM_JOB_ID, region=GCP_LOCATION...
TestVertexAIDeleteCustomTrainingJobOperator
python
getsentry__sentry
src/sentry/identity/gitlab/provider.py
{ "start": 2162, "end": 4581 }
class ____(OAuth2Provider): key = IntegrationProviderSlug.GITLAB.value name = "Gitlab" oauth_scopes = ("api",) def build_identity(self, data): data = data["data"] return { "type": IntegrationProviderSlug.GITLAB.value, "id": data["user"]["id"], "emai...
GitlabIdentityProvider
python
pallets__jinja
src/jinja2/nodes.py
{ "start": 30815, "end": 31123 }
class ____(Expr): """Mark the wrapped expression as safe (wrap it as `Markup`).""" fields = ("expr",) expr: Expr def as_const(self, eval_ctx: EvalContext | None = None) -> Markup: eval_ctx = get_eval_context(self, eval_ctx) return Markup(self.expr.as_const(eval_ctx))
MarkSafe
python
kamyu104__LeetCode-Solutions
Python/teemo-attacking.py
{ "start": 29, "end": 406 }
class ____(object): def findPoisonedDuration(self, timeSeries, duration): """ :type timeSeries: List[int] :type duration: int :rtype: int """ result = duration * len(timeSeries) for i in xrange(1, len(timeSeries)): result -= max(0, duration - (time...
Solution
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mysql/base.py
{ "start": 46480, "end": 72428 }
class ____(compiler.SQLCompiler): dialect: MySQLDialect render_table_with_column_in_update_from = True """Overridden from base SQLCompiler value""" extract_map = compiler.SQLCompiler.extract_map.copy() extract_map.update({"milliseconds": "millisecond"}) def default_from(self) -> str: "...
MySQLCompiler
python
graphql-python__graphene
graphene/types/tests/test_field.py
{ "start": 210, "end": 4104 }
class ____: value = "value" value_func = staticmethod(lambda: "value_func") def value_method(self): return "value_method" def test_field_basic(): MyType = object() args = {"my arg": Argument(True)} def resolver(): return None deprecation_reason = "Deprecated now" des...
MyInstance
python
spack__spack
lib/spack/spack/vendor/jinja2/nodes.py
{ "start": 10492, "end": 11095 }
class ____(Stmt): """The for loop. `target` is the target for the iteration (usually a :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list of nodes that are used as loop-body, and `else_` a list of nodes for the `else` block. If no else node exists it has to be an empty list. ...
For
python
airbytehq__airbyte
airbyte-integrations/connectors/source-rki-covid/source_rki_covid/source.py
{ "start": 6624, "end": 8631 }
class ____(IncrementalRkiCovidStream): """Docs: https://api.corona-zahlen.org/germany/germany/history/incidence/:days""" primary_key = None def __init__(self, config, **kwargs): super().__init__(**kwargs) self.start_date = config.get("start_date") @property def source_defined_curs...
GermanHistoryIncidence
python
huggingface__transformers
src/transformers/models/ernie/modeling_ernie.py
{ "start": 61983, "end": 65530 }
class ____(ErniePreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.ernie = ErnieModel(config, add_pooling_layer=False) self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels) # Initialize weights and ap...
ErnieForQuestionAnswering
python
walkccc__LeetCode
solutions/2641. Cousins in Binary Tree II/2641.py
{ "start": 0, "end": 1026 }
class ____: def replaceValueInTree(self, root: TreeNode | None) -> TreeNode | None: levelSums = [] def dfs(root: TreeNode | None, level: int) -> None: if not root: return if len(levelSums) == level: levelSums.append(0) levelSums[level] += root.val dfs(root.left, level ...
Solution
python
astropy__astropy
astropy/modeling/tests/test_fitting_parallel.py
{ "start": 25357, "end": 33525 }
class ____: def test_basic(self): # Make sure that fitting with units works data = ( gaussian( np.arange(21)[:, None], np.array([2, 1.8]), np.array([5, 10]), np.array([1, 1.1]), ) * u.Jy ) ...
TestUnits
python
astropy__astropy
astropy/time/formats.py
{ "start": 45569, "end": 50386 }
class ____(TimeUnique): """ ymdhms: A Time format to represent Time as year, month, day, hour, minute, second (thus the name ymdhms). Acceptable inputs must have keys or column names in the "YMDHMS" set of ``year``, ``month``, ``day`` ``hour``, ``minute``, ``second``: - Dict with keys in the Y...
TimeYMDHMS
python
spyder-ide__spyder
spyder/plugins/mainmenu/api.py
{ "start": 3559, "end": 3826 }
class ____: Top = 'top_section' Pane = 'pane_section' Toolbar = 'toolbar_section' Layout = 'layout_section' Bottom = 'bottom_section' # For backward compat with plugins targeting Spyder <6.1 ViewMenuSections = WindowMenuSections
WindowMenuSections
python
pennersr__django-allauth
allauth/socialaccount/providers/vk/provider.py
{ "start": 746, "end": 1451 }
class ____(OAuth2Provider): id = "vk" name = "VK" account_class = VKAccount oauth2_adapter_class = VKOAuth2Adapter pkce_enabled_default = True def get_default_scope(self): scope = [] if app_settings.QUERY_EMAIL: scope.append("email") return scope def ext...
VKProvider
python
huggingface__transformers
src/transformers/models/altclip/modeling_altclip.py
{ "start": 16218, "end": 17898 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.layer = nn.ModuleList([AltRobertaLayer(config) for i in range(config.num_hidden_layers)]) self.gradient_checkpointing = False @can_return_tuple def forward( self, ...
AltRobertaEncoder
python
kamyu104__LeetCode-Solutions
Python/convert-sorted-list-to-binary-search-tree.py
{ "start": 292, "end": 1007 }
class ____(object): head = None # @param head, a list node # @return a tree node def sortedListToBST(self, head): current, length = head, 0 while current is not None: current, length = current.next, length + 1 self.head = head return self.sortedListToBSTRecu(0...
Solution
python
tensorflow__tensorflow
tensorflow/python/checkpoint/functional_saver.py
{ "start": 8663, "end": 28095 }
class ____: """Saves checkpoints directly from multiple devices. Note that this is a low-level utility which stores Tensors in the keys specified by `SaveableObject`s. Higher-level utilities for object-based checkpointing are built on top of it. """ def __init__( self, serialized_tensors: Mapp...
MultiDeviceSaver
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-mistral-rs/llama_index/llms/mistral_rs/base.py
{ "start": 2837, "end": 12662 }
class ____(CustomLLM): r""" MistralRS LLM. Examples: Install `mistralrs` following instructions: https://github.com/EricLBuehler/mistral.rs/blob/master/mistralrs-pyo3/README.md#installation-from-pypi Then `pip install llama-index-llms-mistral-rs` This LLM provides automati...
MistralRS
python
PrefectHQ__prefect
src/prefect/testing/fixtures.py
{ "start": 8040, "end": 8290 }
class ____: connections: int path: Optional[str] events: List[Event] token: Optional[str] filter: Optional[EventFilter] def __init__(self): self.connections = 0 self.path = None self.events = []
Recorder
python
google__pytype
pytype/errors/errors_test.py
{ "start": 437, "end": 6509 }
class ____(unittest.TestCase): @errors._error_name(_TEST_ERROR) def test_init(self): e = errors.Error( errors.SEVERITY_ERROR, _MESSAGE, filename="foo.py", line=123, methodname="foo", keyword="here", ) self.assertEqual(errors.SEVERITY_ERROR, e._severity) ...
ErrorTest
python
apache__airflow
task-sdk/src/airflow/sdk/exceptions.py
{ "start": 4281, "end": 4551 }
class ____(_AirflowExecuteWithInactiveAssetExecption): """Raise when the task is executed with inactive assets in its inlet or outlet.""" main_message = "Task has the following inactive assets in its inlets or outlets"
AirflowInactiveAssetInInletOrOutletException
python
django__django
tests/urlpatterns/test_resolvers.py
{ "start": 367, "end": 863 }
class ____(SimpleTestCase): def test_str(self): self.assertEqual(str(RoutePattern(_("translated/"))), "translated/") def test_has_converters(self): self.assertEqual(len(RoutePattern("translated/").converters), 0) self.assertEqual(len(RoutePattern(_("translated/")).converters), 0) ...
RoutePatternTests
python
django__django
tests/model_options/apps.py
{ "start": 346, "end": 441 }
class ____(AppConfig): name = "model_options" default_auto_field = None
ModelPKNoneConfig
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-vertex-endpoint/llama_index/embeddings/vertex_endpoint/base.py
{ "start": 518, "end": 6170 }
class ____(BaseEmbedding): endpoint_id: str = Field(description="Vertex AI endpoint ID") project_id: str = Field(description="GCP Project ID") location: str = Field(description="GCP Region for Vertex AI") endpoint_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additio...
VertexEndpointEmbedding
python
ray-project__ray
rllib/algorithms/dqn/dqn_catalog.py
{ "start": 392, "end": 7426 }
class ____(Catalog): """The catalog class used to build models for DQN Rainbow. `DQNCatalog` provides the following models: - Encoder: The encoder used to encode the observations. - Target_Encoder: The encoder used to encode the observations for the target network. - Af Head...
DQNCatalog
python
huggingface__transformers
tests/utils/test_model_output.py
{ "start": 6424, "end": 6920 }
class ____(unittest.TestCase): def test_direct_model_output(self): # Check that direct usage of ModelOutput instantiates without errors ModelOutput({"a": 1.1}) def test_subclass_no_dataclass(self): # Check that a subclass of ModelOutput without @dataclass is invalid # A valid su...
ModelOutputSubclassTester
python
PrefectHQ__prefect
src/integrations/prefect-redis/prefect_redis/messaging.py
{ "start": 1451, "end": 2236 }
class ____(PrefectBaseSettings): """Settings for the Redis messaging publisher. No settings are required to be set by the user but any of the settings can be overridden by the user using environment variables. Example: ``` PREFECT_REDIS_MESSAGING_PUBLISHER_BATCH_SIZE=10 PREFECT...
RedisMessagingPublisherSettings
python
zarr-developers__zarr-python
src/zarr/codecs/blosc.py
{ "start": 994, "end": 1176 }
class ____(TypedDict): """Configuration for the V2 Blosc codec""" cname: CName clevel: int shuffle: int blocksize: int typesize: NotRequired[int]
BloscConfigV2
python
google__jax
jax/_src/numpy/array_methods.py
{ "start": 32629, "end": 50745 }
class ____: """Helper object to call indexed update functions for an (advanced) index. This object references a source array and a specific indexer into that array. Methods on this object return copies of the source array that have been modified at the positions specified by the indexer. """ __slots__ = ("...
_IndexUpdateRef
python
scipy__scipy
scipy/sparse/tests/test_64bit.py
{ "start": 5304, "end": 6494 }
class ____(RunAll64Bit): # inheritance of pytest test classes does not separate marks for subclasses. # So we define these functions in both Array and Matrix versions. @pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix")) def test_resiliency_limit_10(self, cls, method_name): self....
Test64BitMatrixSameAsArray
python
PyCQA__pylint
tests/functional/r/raising/raising_non_exception.py
{ "start": 282, "end": 378 }
class ____: """Not an actual exception.""" raise Exc from missing # [raising-non-exception]
Exc
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/manyvariants/package.py
{ "start": 217, "end": 1022 }
class ____(Package): """ A package with 4 different variants of different arities to test the `match_variants` argument to `can_splice` """ homepage = "https://www.test.com" has_code = False version("2.0.1") version("2.0.0") version("1.0.1") version("1.0.0") variant("a", d...
Manyvariants
python
pandas-dev__pandas
pandas/tests/window/test_rolling.py
{ "start": 61725, "end": 62205 }
class ____(BaseIndexer): def __init__(self, start, end): self._start = start self._end = end super().__init__() def get_window_bounds( self, num_values=None, min_periods=None, center=None, closed=None, step=None ): if num_values is None: num_values = len(...
PrescribedWindowIndexer
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/ext/hybrid.py
{ "start": 62279, "end": 64567 }
class ____(Comparator[_T]): def __init__( self, cls: Type[Any], expression: Union[_HasClauseElement[_T], SQLColumnExpression[_T]], hybrid: hybrid_property[_T], ): self.cls = cls self.expression = expression self.hybrid = hybrid def __getattr__(self, k...
ExprComparator
python
pydata__xarray
xarray/core/coordinates.py
{ "start": 1247, "end": 6049 }
class ____(Mapping[Hashable, "T_DataArray"]): _data: DataWithCoords __slots__ = ("_data",) def __getitem__(self, key: Hashable) -> T_DataArray: raise NotImplementedError() @property def _names(self) -> set[Hashable]: raise NotImplementedError() @property def dims(self) -> ...
AbstractCoordinates
python
ZoranPandovski__al-go-rithms
data_structures/b_tree/Python/binaryTree.py
{ "start": 108, "end": 226 }
class ____(object): def __init__(self,data=None): self.val = data self.left = self.right = None
Node
python
google__flatbuffers
grpc/examples/python/greeter/server.py
{ "start": 596, "end": 1554 }
class ____(greeter_grpc_fb.GreeterServicer): def __init__(self): self.greetings = ["Hi", "Hallo", "Ciao"] def SayHello(self, request, context): r = HelloRequest.HelloRequest().GetRootAs(request, 0) reply = "Unknown" if r.Name(): reply = r.Name() return build_reply("welcome " + reply.deco...
GreeterServicer
python
pandas-dev__pandas
asv_bench/benchmarks/frame_methods.py
{ "start": 7109, "end": 7608 }
class ____: params = [["dict", "list", "series", "split", "records", "index"]] param_names = ["orient"] def setup(self, orient): data = np.random.randint(0, 1000, size=(10000, 4)) self.int_df = DataFrame(data) self.datetimelike_df = self.int_df.astype("timedelta64[ns]") def tim...
ToDict
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-zhipuai/llama_index/embeddings/zhipuai/base.py
{ "start": 284, "end": 4007 }
class ____(BaseEmbedding): """ ZhipuAI LLM. Visit https://open.bigmodel.cn to get more information about ZhipuAI. Examples: `pip install llama-index-embeddings-zhipuai` ```python from llama_index.embeddings.zhipuai import ZhipuAIEmbedding embedding = ZhipuAIEmbedding(...
ZhipuAIEmbedding
python
pytorch__pytorch
torch/_functorch/_aot_autograd/subclass_parametrization.py
{ "start": 638, "end": 4124 }
class ____(torch.nn.Module): def forward(self, *tensors) -> torch.Tensor: # type: ignore[no-untyped-def] todo: list[torch.Tensor] = list(tensors) def _unwrap_tensor_subclasses(subclass_meta, tensors, offset): # type: ignore[no-untyped-def] if subclass_meta is None: ret...
UnwrapTensorSubclass
python
pytorch__pytorch
torch/fx/passes/shape_prop.py
{ "start": 3294, "end": 8326 }
class ____(torch.fx.Interpreter): """ Execute an FX graph Node-by-Node and record the shape and type of the result into the corresponding node. Example: In this example, we record the shape and data type of a module given an example input ``torch.randn(50, D_in)``. ...
ShapeProp
python
doocs__leetcode
solution/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal/Solution.py
{ "start": 192, "end": 682 }
class ____: def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: def dfs(i: int, j: int, n: int) -> Optional[TreeNode]: if n <= 0: return None v = postorder[j + n - 1] k = d[v] l = dfs(i, j, k - i) r ...
Solution
python
google__jax
jax/experimental/pallas/ops/gpu/hopper_mixed_type_matmul_mgpu.py
{ "start": 1218, "end": 12605 }
class ____: tile_m: int tile_n: int tile_k: int max_concurrent_steps: int epi_tile_n: int | None = 64 # This needs to be lowered for for small N. epi_tile_m: int | None = 64 grid_minor_dim: MatmulDimension = MatmulDimension.N grid_tile_width: int = 1 wg_dimension: MatmulDimension = MatmulDimension.N ...
TuningConfig
python
walkccc__LeetCode
solutions/3470. Permutations IV/3470.py
{ "start": 0, "end": 742 }
class ____: def permute(self, n: int, k: int) -> list[int]: ans = [] isLookingForEven = True remainingNumbers = list(range(1, n + 1)) for turn in range(n): remainingPermutations = (math.factorial((n - 1 - turn) // 2) * math.factorial((n - turn) // 2)) found ...
Solution
python
sqlalchemy__sqlalchemy
test/orm/test_relationships.py
{ "start": 65037, "end": 66717 }
class ____(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "users", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", String(50)), ) Ta...
BackrefPropagatesForwardsArgs
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 15749, "end": 15945 }
class ____(models.Model): name = models.CharField(max_length=30) email = models.EmailField(max_length=255, unique=True) history = HistoricalRecords(table_name="contacts_history")
Contact
python
Pylons__pyramid
tests/test_view.py
{ "start": 6035, "end": 8777 }
class ____(BaseTest, unittest.TestCase): def _makeOne(self, *args, **kw): from pyramid.view import exception_view_config return exception_view_config(*args, **kw) def test_ctor(self): inst = self._makeOne(context=Exception, path_info='path_info') self.assertEqual( i...
Test_exception_view_config
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_autofilter10.py
{ "start": 315, "end": 2701 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("autofilter10.xlsx") self.set_text_file("autofilter_data.txt") def test_create_file(self): """ Test the creation of a simple...
TestCompareXLSXFiles
python
pydantic__pydantic
tests/mypy/outputs/mypy-plugin-strict_ini/plugin_fail.py
{ "start": 1787, "end": 1912 }
class ____(BaseModel, extra=1): # MYPY: error: Invalid value for "Config.extra" [pydantic-config] pass
KwargsBadExtraModel
python
readthedocs__readthedocs.org
readthedocs/builds/migrations/0021_make_hidden_field_not_null.py
{ "start": 149, "end": 651 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("builds", "0020_migrate_null_hidden_field"), ] operations = [ migrations.AlterField( model_name="version", name="hidden", field=models.BooleanField( default...
Migration
python
coleifer__peewee
tests/models.py
{ "start": 100180, "end": 110788 }
class ____(ModelTestCase): requires = [Category] def setUp(self): super(TestCTEIntegration, self).setUp() CC = Category.create root = CC(name='root') p1 = CC(name='p1', parent=root) p2 = CC(name='p2', parent=root) p3 = CC(name='p3', parent=root) c11 = CC(...
TestCTEIntegration
python
sympy__sympy
sympy/stats/random_matrix_models.py
{ "start": 3950, "end": 4647 }
class ____(GaussianEnsembleModel): @property def normalization_constant(self): n = self.dimension return 2**(S(n)/2) * pi**(S(n**2)/2) def density(self, expr): n, ZGUE = self.dimension, self.normalization_constant h_pspace = RandomMatrixPSpace('P', model=self) H = Ra...
GaussianUnitaryEnsembleModel
python
sympy__sympy
sympy/core/numbers.py
{ "start": 95258, "end": 96660 }
class ____(IntegerConstant, metaclass=Singleton): """The number negative one. NegativeOne is a singleton, and can be accessed by ``S.NegativeOne``. Examples ======== >>> from sympy import S, Integer >>> Integer(-1) is S.NegativeOne True See Also ======== One References ...
NegativeOne
python
Unity-Technologies__ml-agents
ml-agents-envs/tests/simple_test_envs.py
{ "start": 934, "end": 10473 }
class ____(BaseEnv): """ Very simple "game" - the agent has a position on [-1, 1], gets a reward of 1 if it reaches 1, and a reward of -1 if it reaches -1. The position is incremented by the action amount (clamped to [-step_size, step_size]). """ def __init__( self, brain_names, ...
SimpleEnvironment
python
PrefectHQ__prefect
tests/server/orchestration/api/test_variables.py
{ "start": 21248, "end": 21857 }
class ____: async def test_delete_variable( self, client: AsyncClient, variable, ): res = await client.delete( f"/variables/name/{variable.name}", ) assert res.status_code == 204 res = await client.get( f"/variables/name/{variable.n...
TestDeleteVariableByName
python
crytic__slither
slither/detectors/statements/deprecated_calls.py
{ "start": 773, "end": 7788 }
class ____(AbstractDetector): """ Use of Deprecated Standards """ ARGUMENT = "deprecated-standards" HELP = "Deprecated Solidity Standards" IMPACT = DetectorClassification.INFORMATIONAL CONFIDENCE = DetectorClassification.HIGH LANGUAGE = "solidity" WIKI = "https://github.com/crytic/s...
DeprecatedStandards
python
doocs__leetcode
lcof2/剑指 Offer II 102. 加减的目标值/Solution.py
{ "start": 0, "end": 581 }
class ____: def findTargetSumWays(self, nums: List[int], target: int) -> int: if target < -1000 or target > 1000: return 0 n = len(nums) dp = [[0] * 2001 for i in range(n)] dp[0][nums[0] + 1000] += 1 dp[0][-nums[0] + 1000] += 1 for i in range(1, n): ...
Solution
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI046.py
{ "start": 90, "end": 155 }
class ____(typing.Protocol): bar: int _T = TypeVar("_T")
_Bar
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 9336, "end": 9568 }
class ____(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) choice = models.ForeignKey(Choice, on_delete=models.CASCADE, related_name="voters") def __str__(self): return "Voter object"
Voter
python
ray-project__ray
python/ray/llm/tests/serve/utils/testing_utils.py
{ "start": 403, "end": 7643 }
class ____: """Reusable validation logic for LLM responses.""" @staticmethod def get_expected_content( api_type: str, max_tokens: int, lora_model_id: str = "" ) -> str: """Get expected content based on API type.""" expected_content = " ".join(f"test_{i}" for i in range(max_token...
LLMResponseValidator
python
dagster-io__dagster
python_modules/libraries/dagster-k8s/dagster_k8s/executor.py
{ "start": 8650, "end": 17354 }
class ____(StepHandler): @property def name(self): return "K8sStepHandler" def __init__( self, image: Optional[str], container_context: K8sContainerContext, load_incluster_config: bool, kubeconfig_file: Optional[str], k8s_client_batch_api=None, ...
K8sStepHandler
python
keras-team__keras
keras/src/utils/backend_utils_test.py
{ "start": 163, "end": 1847 }
class ____(testing.TestCase): @parameterized.named_parameters( ("numpy", "numpy"), ("jax", "jax"), ("tensorflow", "tensorflow"), ("torch", "torch"), ) def test_dynamic_backend(self, name): dynamic_backend = backend_utils.DynamicBackend() x = np.random.uniform(...
BackendUtilsTest
python
pandas-dev__pandas
pandas/tests/extension/array_with_attr/array.py
{ "start": 702, "end": 2481 }
class ____(ExtensionArray): dtype = FloatAttrDtype() __array_priority__ = 1000 def __init__(self, values, attr=None) -> None: if not isinstance(values, np.ndarray): raise TypeError("Need to pass a numpy array of float64 dtype as values") if not values.dtype == "float64": ...
FloatAttrArray
python
huggingface__transformers
tests/models/roformer/test_tokenization_roformer.py
{ "start": 880, "end": 3802 }
class ____(TokenizerTesterMixin, unittest.TestCase): from_pretrained_id = "junnyu/roformer_chinese_small" tokenizer_class = RoFormerTokenizer rust_tokenizer_class = RoFormerTokenizerFast space_between_special_tokens = True test_rust_tokenizer = True @classmethod def setUpClass(cls): ...
RoFormerTokenizationTest
python
pytorch__pytorch
test/test_privateuseone_python_backend.py
{ "start": 3411, "end": 4093 }
class ____(TestCase): @classmethod def setupClass(cls): pass def test_accessing_is_pinned(self): a_cpu = torch.randn((2, 2)) # Assert this don't throw: _ = a_cpu.is_pinned() def test_backend_simple(self): a_cpu = torch.randn((2, 2)) b_cpu = torch.randn((...
PrivateUse1BackendTest
python
scipy__scipy
scipy/cluster/tests/test_hierarchy.py
{ "start": 30028, "end": 32985 }
class ____: def test_is_monotonic_empty(self, xp): # Tests is_monotonic(Z) on an empty linkage. Z = xp.zeros((0, 4), dtype=xp.float64) assert_raises(ValueError, is_monotonic, Z) def test_is_monotonic_1x4(self, xp): # Tests is_monotonic(Z) on 1x4 linkage. Expecting True. ...
TestIsMonotonic
python
apache__airflow
providers/qdrant/src/airflow/providers/qdrant/hooks/qdrant.py
{ "start": 1070, "end": 4938 }
class ____(BaseHook): """ Hook for interfacing with a Qdrant instance. :param conn_id: The connection id to use when connecting to Qdrant. Defaults to `qdrant_default`. """ conn_name_attr = "conn_id" conn_type = "qdrant" default_conn_name = "qdrant_default" hook_name = "Qdrant" @c...
QdrantHook
python
pytorch__pytorch
test/distributed/tensor/parallel/test_micro_pipeline_tp.py
{ "start": 18500, "end": 20336 }
class ____(TestCase): def setUp(self): torch._inductor.config._micro_pipeline_tp = True self.rank = 0 self.world_size = 4 torch.cuda.set_device("cuda:0") store = FakeStore() dist.init_process_group( backend="fake", world_size=self.world_size,...
MicroPipelineTP4GPUTest
python
lepture__authlib
authlib/deprecate.py
{ "start": 18, "end": 506 }
class ____(DeprecationWarning): pass warnings.simplefilter("always", AuthlibDeprecationWarning) def deprecate(message, version=None, link_uid=None, link_file=None, stacklevel=3): if version: message += f"\nIt will be compatible before version {version}." if link_uid and link_file: messa...
AuthlibDeprecationWarning
python
bokeh__bokeh
src/bokeh/models/mappers.py
{ "start": 9071, "end": 9952 }
class ____(ContinuousColorMapper): ''' Map numbers in a range [*low*, *high*] into a sequence of colors (a palette) on a natural logarithm scale. For example, if the range is [0, 25] and the palette is ``['red', 'green', 'blue']``, the values would be mapped as follows:: x < 0 : 'r...
LogColorMapper