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 | chroma-core__chroma | chromadb/errors.py | {
"start": 1574,
"end": 1709
} | class ____(ChromaError):
@classmethod
@overrides
def name(cls) -> str:
return "InvalidHTTPVersion"
| InvalidHTTPVersion |
python | google__jax | jax/_src/pallas/core.py | {
"start": 8297,
"end": 8675
} | class ____:
grid: GridMappingGrid
mapped_dims: tuple[int, ...]
def size(self, axis: int) -> int | DynamicGridDim:
valid_grid = tuple(self.grid)
try:
size = valid_grid[axis]
except IndexError as e:
raise ValueError(
f"Axis {axis} is out of bounds for grid {self.grid}"
) fro... | PallasGridContext |
python | pydata__xarray | xarray/compat/pdcompat.py | {
"start": 2130,
"end": 3474
} | class ____(Enum):
"""Used by pandas to specify a default value for a deprecated argument.
Copied from pandas._libs.lib._NoDefault.
See also:
- pandas-dev/pandas#30788
- pandas-dev/pandas#40684
- pandas-dev/pandas#40715
- pandas-dev/pandas#47045
"""
no_default = "NO_DEFAULT"
de... | _NoDefault |
python | getsentry__sentry | tests/sentry/issues/endpoints/test_group_event_details.py | {
"start": 6887,
"end": 17214
} | class ____(
GroupEventDetailsEndpointTestBase, APITestCase, SnubaTestCase, OccurrenceTestMixin
):
def test_get_simple_helpful(self) -> None:
self.event_d = self.store_event(
data={
"event_id": "d" * 32,
"environment": "staging",
"timestamp": be... | GroupEventDetailsHelpfulEndpointTest |
python | pytorch__pytorch | test/test_fx_passes.py | {
"start": 24320,
"end": 24936
} | class ____:
# This test case is for pattern where no matching anchor is found in the target graph
# `anchor` is the starting point of the pattern matching, it's usually the boundary returning nodes
@staticmethod
def forward(x):
x = x + 1
return x
@staticmethod
def pattern(a):
... | NoAnchorFound |
python | apache__airflow | devel-common/src/sphinx_exts/docs_build/spelling_checks.py | {
"start": 1338,
"end": 7345
} | class ____(NamedTuple):
"""Spelling errors found when building docs."""
file_path: Path | None
line_no: int | None
spelling: str | None
suggestion: str | None
context_line: str | None
message: str
def __eq__(self, other):
left = (
self.file_path,
self.li... | SpellingError |
python | charliermarsh__ruff | crates/ty_python_semantic/resources/corpus/cyclic_reassignment.py | {
"start": 0,
"end": 67
} | class ____[_: foo](object): ...
[_] = (foo,) = foo
def foo(): ...
| foo |
python | spack__spack | lib/spack/spack/vendor/jinja2/nodes.py | {
"start": 33168,
"end": 33705
} | class ____(Stmt):
"""An overlay scope for extensions. This is a largely unoptimized scope
that however can be used to introduce completely arbitrary variables into
a sub scope from a dictionary or dictionary like object. The `context`
field has to evaluate to a dictionary object.
Example usage::
... | OverlayScope |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/nocover/test_drypython_returns.py | {
"start": 2736,
"end": 2812
} | class ____(_FirstBase[A, str], _SecondBase[float, D]):
pass
| MixedGenerics2 |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/metadata.py | {
"start": 5683,
"end": 6746
} | class ____(graphene.ObjectType):
pool = graphene.NonNull(graphene.String)
class Meta:
interfaces = (GrapheneMetadataEntry,)
name = "PoolMetadataEntry"
def types():
return [
GrapheneMetadataEntry,
GrapheneTableColumnLineageMetadataEntry,
GrapheneTableSchemaMetadataE... | GraphenePoolMetadataEntry |
python | paramiko__paramiko | paramiko/client.py | {
"start": 1462,
"end": 31919
} | class ____(ClosingContextManager):
"""
A high-level representation of a session with an SSH server. This class
wraps `.Transport`, `.Channel`, and `.SFTPClient` to take care of most
aspects of authenticating and opening channels. A typical use case is::
client = SSHClient()
client.loa... | SSHClient |
python | getsentry__sentry | src/sentry/api/serializers/release_details_types.py | {
"start": 1870,
"end": 1917
} | class ____(BaseProject):
newGroups: int
| Project |
python | ray-project__ray | python/ray/tests/gpu_objects/test_gpu_objects_nixl.py | {
"start": 186,
"end": 8366
} | class ____:
def __init__(self):
self.reserved_tensor1 = torch.tensor([1, 2, 3]).to("cuda")
self.reserved_tensor2 = torch.tensor([4, 5, 6]).to("cuda")
self.reserved_tensor3 = torch.tensor([7, 8, 9]).to("cuda")
@ray.method(tensor_transport="nixl")
def echo(self, data, device):
... | GPUTestActor |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-gitlab/unit_tests/test_config_migrations.py | {
"start": 2034,
"end": 3349
} | class ____:
def test_given_valid_api_url_then_no_exception_is_raised(self, oauth_config):
config = dict(oauth_config)
config["api_url"] = "https://gitlab.com"
source = get_source(config=config, config_path=None)
migrated_config = source.configure(config=config, temp_dir="/not/a/real/... | TestValidations |
python | getsentry__sentry | src/sentry/spans/grouping/strategy/base.py | {
"start": 323,
"end": 1158
} | class ____(TypedDict):
trace_id: str
parent_span_id: str
span_id: str
is_segment: NotRequired[bool]
start_timestamp: float
timestamp: float
same_process_as_parent: bool
op: str
description: str | None
fingerprint: Sequence[str] | None
tags: Any | None
data: Any | None
... | Span |
python | walkccc__LeetCode | solutions/1721. Swapping Nodes in a Linked List/1721.py | {
"start": 0,
"end": 397
} | class ____:
def swapNodes(self, head: ListNode | None, k: int) -> ListNode | None:
p = None # Points the k-th node from the beginning.
q = None # Points the k-th node from the end.
curr = head
while curr:
if q:
q = q.next
k -= 1
if k == 0:
p = curr
q = head... | Solution |
python | modin-project__modin | asv_bench/benchmarks/benchmarks.py | {
"start": 15465,
"end": 15972
} | class ____:
param_names = ["shape", "head_count"]
params = [
get_benchmark_shapes("TimeHead"),
[5, 0.8],
]
def setup(self, shape, head_count):
self.df = generate_dataframe("int", *shape, RAND_LOW, RAND_HIGH)
self.head_count = (
int(head_count * len(self.df.in... | TimeHead |
python | langchain-ai__langchain | libs/core/langchain_core/load/serializable.py | {
"start": 2203,
"end": 11683
} | class ____(BaseModel, ABC):
"""Serializable base class.
This class is used to serialize objects to JSON.
It relies on the following methods and properties:
- `is_lc_serializable`: Is this class serializable?
By design, even if a class inherits from `Serializable`, it is not serializable
... | Serializable |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/cachecontrol/filewrapper.py | {
"start": 281,
"end": 4292
} | class ____:
"""
Small wrapper around a fp object which will tee everything read into a
buffer, and when that file is closed it will execute a callback with the
contents of that buffer.
All attributes are proxied to the underlying file object.
This class uses members with a double underscore (_... | CallbackFileWrapper |
python | langchain-ai__langchain | libs/partners/ollama/tests/integration_tests/chat_models/test_chat_models_standard.py | {
"start": 300,
"end": 1956
} | class ____(ChatModelIntegrationTests):
@property
def chat_model_class(self) -> type[ChatOllama]:
return ChatOllama
@property
def chat_model_params(self) -> dict:
return {"model": DEFAULT_MODEL_NAME}
@property
def supports_json_mode(self) -> bool:
return True
@prope... | TestChatOllama |
python | openai__openai-python | src/openai/types/fine_tuning/jobs/fine_tuning_job_checkpoint.py | {
"start": 240,
"end": 596
} | class ____(BaseModel):
full_valid_loss: Optional[float] = None
full_valid_mean_token_accuracy: Optional[float] = None
step: Optional[float] = None
train_loss: Optional[float] = None
train_mean_token_accuracy: Optional[float] = None
valid_loss: Optional[float] = None
valid_mean_token_ac... | Metrics |
python | ansible__ansible | lib/ansible/cli/doc.py | {
"start": 17321,
"end": 73077
} | class ____(CLI, RoleMixin):
""" displays information on modules installed in Ansible libraries.
It displays a terse listing of plugins and their short descriptions,
provides a printout of their DOCUMENTATION strings,
and it can create a short "snippet" which can be pasted into a playbook. "... | DocCLI |
python | sphinx-doc__sphinx | sphinx/ext/inheritance_diagram.py | {
"start": 12658,
"end": 19049
} | class ____(SphinxDirective):
"""Run when the inheritance_diagram directive is first encountered."""
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec: ClassVar[OptionSpec] = {
'parts': int,
'private-bases': directives.... | InheritanceDiagram |
python | huggingface__transformers | tests/trainer/test_trainer_utils.py | {
"start": 2798,
"end": 23191
} | class ____(unittest.TestCase):
def test_label_smoothing(self):
epsilon = 0.1
num_labels = 12
random_logits = torch.randn(4, 5, num_labels)
random_labels = torch.randint(0, num_labels, (4, 5))
loss = nn.functional.cross_entropy(random_logits.view(-1, num_labels), random_labels... | TrainerUtilsTest |
python | pytorch__pytorch | test/export/test_package.py | {
"start": 341,
"end": 2853
} | class ____(TestCase):
def test_basic(self):
def fn(x: torch.Tensor) -> torch.Tensor:
return x + 1
x = torch.randn(3, 2)
package = _ExportPackage()
self.assertEqual(
package._exporter("fn", fn)(x),
fn(x),
)
self.assertEqual(len(pack... | TestPackage |
python | scipy__scipy | scipy/optimize/tests/test_minpack.py | {
"start": 7106,
"end": 8509
} | class ____:
def test_pressure_network_no_gradient(self):
# root/hybr without gradient, equal pipes -> equal flows
k = np.full(4, 0.5)
Qtot = 4
initial_guess = array([2., 0., 2., 0.])
final_flows = optimize.root(pressure_network, initial_guess,
... | TestRootHybr |
python | bokeh__bokeh | src/bokeh/models/annotations/dimensional.py | {
"start": 3319,
"end": 4203
} | class ____(Dimensional):
""" Model for defining metric units of measurement.
"""
# explicit __init__ to support Init signatures
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
base_unit = Required(String, help="""
The short name of the base unit, e.g. ``"m"`` for ... | Metric |
python | pytorch__pytorch | test/test_functional_optim.py | {
"start": 311,
"end": 686
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
torch.manual_seed(0)
self.lin1 = nn.Linear(3, 3, bias=False)
self.lin2 = nn.Linear(3, 3, bias=False)
def forward(self, t1):
return self.lin2(F.relu(self.lin1(t1)))
# dummy class to showcase cus... | MyModule |
python | cython__cython | Cython/Compiler/Optimize.py | {
"start": 226982,
"end": 228260
} | class ____(Visitor.CythonTransform):
"""
This class facilitates the sharing of overflow checking among all nodes
of a nested arithmetic expression. For example, given the expression
a*b + c, where a, b, and x are all possibly overflowing ints, the entire
sequence will be evaluated and the overflow ... | ConsolidateOverflowCheck |
python | huggingface__transformers | src/transformers/activations.py | {
"start": 7780,
"end": 8001
} | class ____(OrderedDict):
def __getitem__(self, key):
content = super().__getitem__(key)
cls, kwargs = content if isinstance(content, tuple) else (content, {})
return cls(**kwargs)
| ClassInstantier |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/metadata_service/models/generated/ConnectorRegistryDestinationDefinition.py | {
"start": 8170,
"end": 10357
} | class ____(BaseModel):
class Config:
extra = Extra.allow
destinationDefinitionId: UUID
name: str
dockerRepository: str
dockerImageTag: str
documentationUrl: str
icon: Optional[str] = None
iconUrl: Optional[str] = None
spec: Dict[str, Any]
tombstone: Optional[bool] = Fiel... | ConnectorRegistryDestinationDefinition |
python | django__django | django/contrib/gis/gdal/raster/band.py | {
"start": 439,
"end": 7836
} | class ____(GDALRasterBase):
"""
Wrap a GDAL raster band, needs to be obtained from a GDALRaster object.
"""
def __init__(self, source, index):
self.source = source
self._ptr = capi.get_ds_raster_band(source._ptr, index)
def _flush(self):
"""
Call the flush method on... | GDALBand |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-of-consecutive-values-you-can-make.py | {
"start": 33,
"end": 335
} | class ____(object):
def getMaximumConsecutive(self, coins):
"""
:type coins: List[int]
:rtype: int
"""
coins.sort()
result = 1
for c in coins:
if c > result:
break
result += c
return result
| Solution |
python | getsentry__sentry | src/sentry/api/endpoints/artifact_lookup.py | {
"start": 1817,
"end": 11046
} | class ____(ProjectEndpoint):
owner = ApiOwner.OWNERS_INGEST
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
permission_classes = (ProjectReleasePermission,)
def download_file(self, download_id, project: Project):
split = download_id.split("/")
if len(split) < 2:
... | ProjectArtifactLookupEndpoint |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/partition_status_cache.py | {
"start": 1609,
"end": 2412
} | class ____(Enum):
"""The status of asset partition."""
MATERIALIZED = "MATERIALIZED"
IN_PROGRESS = "IN_PROGRESS"
FAILED = "FAILED"
def is_cacheable_partition_type(partitions_def: PartitionsDefinition) -> bool:
check.inst_param(partitions_def, "partitions_def", PartitionsDefinition)
if not isi... | AssetPartitionStatus |
python | dask__distributed | distributed/comm/tcp.py | {
"start": 26285,
"end": 26391
} | class ____(BaseTCPBackend):
_connector_class = TCPConnector
_listener_class = TCPListener
| TCPBackend |
python | openai__openai-python | tests/test_transform.py | {
"start": 4755,
"end": 4854
} | class ____(TypedDict, total=False):
foo: Annotated[date, PropertyInfo(format="iso8601")]
| DateDict |
python | apache__airflow | providers/imap/src/airflow/providers/imap/hooks/imap.py | {
"start": 1362,
"end": 12152
} | class ____(BaseHook):
"""
This hook connects to a mail server by using the imap protocol.
.. note:: Please call this Hook as context manager via `with`
to automatically open and close the connection to the mail server.
:param imap_conn_id: The :ref:`imap connection id <howto/connection:imap>`
... | ImapHook |
python | modin-project__modin | modin/core/io/column_stores/parquet_dispatcher.py | {
"start": 1579,
"end": 6124
} | class ____:
"""
Base class that encapsulates Parquet engine-specific details.
This class exposes a set of functions that are commonly used in the
`read_parquet` implementation.
Attributes
----------
path : str, path object or file-like object
The filepath of the parquet file in loc... | ColumnStoreDataset |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 361816,
"end": 362929
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of UpdateProjectV2"""
__schema__ = github_schema
__field_names__ = ("project_id", "title", "short_description", "readme", "closed", "public", "client_mutation_id")
project_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="projectId... | UpdateProjectV2Input |
python | apache__airflow | providers/cloudant/src/airflow/providers/cloudant/hooks/cloudant.py | {
"start": 1121,
"end": 3492
} | class ____(BaseHook):
"""
Interact with Cloudant. This class is a thin wrapper around the cloudant python library.
.. seealso:: the latest documentation `here <https://python-cloudant.readthedocs.io/en/latest/>`_.
:param cloudant_conn_id: The connection id to authenticate and get a session object from... | CloudantHook |
python | google__pytype | pytype/load_pytd_test.py | {
"start": 1554,
"end": 30104
} | class ____(_LoaderTest):
"""Tests for load_pytd.py."""
def test_filepath_to_module(self):
# (filename, pythonpath, expected)
test_cases = [
("foo/bar/baz.py", [""], "foo.bar.baz"),
("foo/bar/baz.py", ["foo"], "bar.baz"),
("foo/bar/baz.py", ["fo"], "foo.bar.baz"),
("foo/bar/b... | ImportPathsTest |
python | pytorch__pytorch | tools/linter/adapters/test_device_bias_linter.py | {
"start": 636,
"end": 2401
} | class ____(NamedTuple):
path: str | None
line: int | None
char: int | None
code: str
severity: LintSeverity
name: str
original: str | None
replacement: str | None
description: str | None
DEVICE_BIAS = ["cuda", "xpu", "mps"]
GPU_RELATED_DECORATORS = {"requires_gpu", "requires_triton... | LintMessage |
python | django__django | tests/postgres_tests/models.py | {
"start": 1734,
"end": 1842
} | class ____(PostgreSQLModel):
field = ArrayField(ArrayField(models.IntegerField()))
| NestedIntegerArrayModel |
python | pytorch__pytorch | torch/_dynamo/variables/misc.py | {
"start": 66710,
"end": 66797
} | class ____(VariableTracker):
"""Marker used to implement delattr()"""
| DeletedVariable |
python | python__mypy | mypy/test/testtypes.py | {
"start": 62183,
"end": 62821
} | class ____(TestCase):
# WARNING: do not increase this number unless absolutely necessary,
# and you understand what you are doing.
ALLOWED_GET_PROPER_TYPES = 7
@skipUnless(mypy.expandtype.__file__.endswith(".py"), "Skip for compiled mypy")
def test_count_get_proper_type(self) -> None:
with ... | TestExpandTypeLimitGetProperType |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 24536,
"end": 24994
} | class ____(DelegatingLexer):
"""
Subclass of the `MakoLexer` that highlights unlexed data
with the `CssLexer`.
.. versionadded:: 0.7
"""
name = 'CSS+Mako'
aliases = ['css+mako']
mimetypes = ['text/css+mako']
def __init__(self, **options):
super(MakoCssLexer, self).__init__... | MakoCssLexer |
python | TheAlgorithms__Python | data_structures/binary_tree/flatten_binarytree_to_linkedlist.py | {
"start": 456,
"end": 3408
} | class ____:
"""
A TreeNode has data variable and pointers to TreeNode objects
for its left and right children.
"""
def __init__(self, data: int) -> None:
self.data = data
self.left: TreeNode | None = None
self.right: TreeNode | None = None
def build_tree() -> TreeNode:
... | TreeNode |
python | lxml__lxml | src/lxml/html/diff.py | {
"start": 32304,
"end": 32989
} | class ____(SequenceMatcher):
"""
Acts like SequenceMatcher, but tries not to find very small equal
blocks amidst large spans of changes
"""
threshold = 2
@cython.cfunc
def get_matching_blocks(self) -> list:
size: cython.Py_ssize_t = min(len(self.b), len(self.b))
threshold: ... | InsensitiveSequenceMatcher |
python | mlflow__mlflow | mlflow/server/graphql/graphql_schema_extensions.py | {
"start": 986,
"end": 1852
} | class ____(MlflowRun):
experiment = graphene.Field(MlflowExperiment)
model_versions = graphene.List(graphene.NonNull(MlflowModelVersion))
def resolve_experiment(self, info):
experiment_id = self.info.experiment_id
input_dict = {"experiment_id": experiment_id}
request_message = mlflo... | MlflowRunExtension |
python | streamlit__streamlit | lib/streamlit/elements/widgets/time_widgets.py | {
"start": 14357,
"end": 14842
} | class ____:
value: time | None
def deserialize(self, ui_value: str | None) -> time | None:
return (
datetime.strptime(ui_value, "%H:%M").time()
if ui_value is not None
else self.value
)
def serialize(self, v: datetime | time | None) -> str | None:
... | TimeInputSerde |
python | django__django | tests/admin_inlines/models.py | {
"start": 9028,
"end": 9110
} | class ____(Course):
class Meta:
proxy = True
# Other models
| CourseProxy2 |
python | fluentpython__example-code | 21-class-metaprog/bulkfood/model_v8.py | {
"start": 1901,
"end": 2113
} | class ____(metaclass=EntityMeta):
"""Business entity with validated fields"""
@classmethod
def field_names(cls): # <5>
for name in cls._field_names:
yield name
# END MODEL_V8
| Entity |
python | streamlit__streamlit | lib/streamlit/testing/v1/element_tree.py | {
"start": 34408,
"end": 36016
} | class ____(Widget, Generic[SliderValueT]):
"""A representation of ``st.slider``."""
_value: SliderValueT | Sequence[SliderValueT] | None
proto: SliderProto = field(repr=False)
label: str
data_type: SliderProto.DataType.ValueType
min: SliderValueT
max: SliderValueT
step: SliderStep
... | Slider |
python | ray-project__ray | rllib/examples/connectors/classes/euclidian_distance_based_curiosity.py | {
"start": 277,
"end": 4959
} | class ____(ConnectorV2):
"""Learner ConnectorV2 piece computing intrinsic rewards with euclidian distance.
Add this connector piece to your Learner pipeline, through your algo config:
```
config.training(
learner_connector=lambda obs_sp, act_sp: EuclidianDistanceBasedCuriosity()
)
```
... | EuclidianDistanceBasedCuriosity |
python | PyCQA__flake8 | src/flake8/exceptions.py | {
"start": 249,
"end": 345
} | class ____(Flake8Exception):
"""Exception raised during execution of Flake8."""
| ExecutionError |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1004148,
"end": 1004676
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of TransferEnterpriseOrganization"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "organization")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client p... | TransferEnterpriseOrganizationPayload |
python | charliermarsh__ruff | scripts/update_schemastore.py | {
"start": 984,
"end": 5215
} | class ____(enum.Enum):
SSH = "ssh"
HTTPS = "https"
def schemastore_repos(self) -> SchemastoreRepos:
match self:
case GitProtocol.SSH:
return SchemastoreRepos(
fork="git@github.com:astral-sh/schemastore.git",
upstream="git@github.co... | GitProtocol |
python | django__django | tests/admin_views/admin.py | {
"start": 13398,
"end": 13470
} | class ____(admin.StackedInline):
model = FancyDoodad
| FancyDoodadInline |
python | langchain-ai__langchain | libs/text-splitters/langchain_text_splitters/json.py | {
"start": 159,
"end": 5876
} | class ____:
"""Splits JSON data into smaller, structured chunks while preserving hierarchy.
This class provides methods to split JSON data into smaller dictionaries or
JSON-formatted strings based on configurable maximum and minimum chunk sizes.
It supports nested JSON structures, optionally converts l... | RecursiveJsonSplitter |
python | ray-project__ray | rllib/examples/centralized_critic.py | {
"start": 3082,
"end": 8236
} | class ____:
"""Add method to evaluate the central value function from the model."""
def __init__(self):
if self.config["framework"] != "torch":
self.compute_central_vf = make_tf_callable(self.get_session())(
self.model.central_value_function
)
else:
... | CentralizedValueMixin |
python | PyCQA__pylint | pylint/exceptions.py | {
"start": 1243,
"end": 1352
} | class ____(Exception):
"""Raised when a report is empty and so should not be displayed."""
| EmptyReportError |
python | google__pytype | pytype/imports/builtin_stubs.py | {
"start": 1287,
"end": 3291
} | class ____:
"""The builtins and typing modules, which need to be treated specially."""
def _parse_predefined(self, name, options):
_, src = GetPredefinedFile("builtins", name, ".pytd")
mod = parser.parse_string(src, name=name, options=options)
return mod
def load(self, options):
"""Read builtins... | BuiltinsAndTyping |
python | kamyu104__LeetCode-Solutions | Python/binary-tree-longest-consecutive-sequence.py | {
"start": 29,
"end": 813
} | class ____(object):
def longestConsecutive(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.max_len = 0
def longestConsecutiveHelper(root):
if not root:
return 0
left_len = longestConsecutiveHelper(root.left)
... | Solution |
python | Textualize__textual | src/textual/events.py | {
"start": 23921,
"end": 24058
} | class ____(Event, bubble=False):
"""Sent to screen that has been made active.
- [ ] Bubbles
- [ ] Verbose
"""
| ScreenResume |
python | walkccc__LeetCode | solutions/2747. Count Zero Request Servers/2747.py | {
"start": 183,
"end": 1067
} | class ____:
def countServers(
self,
n: int,
logs: list[list[int]],
x: int,
queries: list[int],
) -> list[int]:
ans = [0] * len(queries)
count = [0] * (n + 1)
logs.sort(key=lambda x: x[1])
i = 0
j = 0
servers = 0
# For each query, we care about logs[i..j].... | Solution |
python | django__django | tests/model_inheritance_regress/models.py | {
"start": 2076,
"end": 2158
} | class ____(Article):
author = models.CharField(max_length=100)
| ArticleWithAuthor |
python | huggingface__transformers | src/transformers/models/time_series_transformer/modeling_time_series_transformer.py | {
"start": 18626,
"end": 21823
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: TimeSeriesTransformerConfig, layer_idx: Optional[int] = None):
super().__init__()
self.embed_dim = config.d_model
self.self_attn = TimeSeriesTransformerAttention(
embed_dim=self.embed_dim,
num_heads=c... | TimeSeriesTransformerEncoderLayer |
python | spack__spack | lib/spack/spack/url_buildcache.py | {
"start": 1422,
"end": 2309
} | class ____(enum.Enum):
"""Enumeration of the kinds of things that live in a URL buildcache
These enums serve two purposes: They allow different buildcache layout
versions to specify different relative location of these entities, and
they're used to map buildcache objects to their respective media types... | BuildcacheComponent |
python | pypa__warehouse | warehouse/accounts/security_policy.py | {
"start": 4251,
"end": 8817
} | class ____:
"""The BasicAuthSecurityPolicy is no longer allowed
and raises a message when used for uploads when it's not an API Token"""
def identity(self, request):
# If we're calling into this API on a request, then we want to register
# a callback which will ensure that the response vari... | BasicAuthSecurityPolicy |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py | {
"start": 30640,
"end": 30908
} | class ____(graphene.Union):
"""The output from logging telemetry."""
class Meta:
types = (
GrapheneLogTelemetrySuccess,
GraphenePythonError,
)
name = "LogTelemetryMutationResult"
| GrapheneLogTelemetryMutationResult |
python | google__pytype | pytype/test_data/pytree.py | {
"start": 17740,
"end": 19033
} | class ____(BasePattern):
def __init__(self, type=None, content=None, name=None):
"""Initializer. Takes optional type, content, and name.
The type, if given must be a token type (< 256). If not given,
this matches any *leaf* node; the content may still be required.
The content, if given, must be a ... | LeafPattern |
python | PrefectHQ__prefect | src/integrations/prefect-kubernetes/tests/test_logging.py | {
"start": 117,
"end": 7275
} | class ____:
"""Tests for the KopfObjectJsonFormatter"""
def test_filters_unserializable_kopf_fields(self):
"""
Test that kopf-specific fields (k8s_skip, k8s_ref, settings) are
filtered out from the log record.
"""
formatter = KopfObjectJsonFormatter()
# Create a... | TestKopfObjectJsonFormatter |
python | pypa__warehouse | warehouse/classifiers/models.py | {
"start": 199,
"end": 609
} | class ____(db.ModelBase):
__tablename__ = "trove_classifiers"
__tableargs__ = CheckConstraint(
"classifier not ilike 'private ::%'",
name="ck_disallow_private_top_level_classifier",
)
__repr__ = make_repr("classifier")
id: Mapped[int] = mapped_column(primary_key=True)
classifie... | Classifier |
python | pypa__warehouse | warehouse/admin/views/organizations.py | {
"start": 2081,
"end": 3569
} | class ____(wtforms.Form):
display_name = wtforms.StringField(
validators=[
wtforms.validators.InputRequired(
message="Specify organization display name"
),
wtforms.validators.Length(
max=100,
message="Organization display na... | OrganizationForm |
python | marshmallow-code__marshmallow | src/marshmallow/fields.py | {
"start": 69322,
"end": 71325
} | class ____(Field):
"""A field that takes the value returned by a function.
:param serialize: A callable from which to retrieve the value.
The function must take a single argument ``obj`` which is the object
to be serialized.
If no callable is provided then the ```load_only``` flag will ... | Function |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_data_validation01.py | {
"start": 315,
"end": 962
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("data_validation01.xlsx")
def test_create_file(self):
"""Test the creation of a XlsxWriter file with data validation."""
workbook =... | TestCompareXLSXFiles |
python | pypa__pip | src/pip/_vendor/urllib3/contrib/socks.py | {
"start": 2327,
"end": 5042
} | class ____(HTTPConnection):
"""
A plain-text HTTP connection that connects via a SOCKS proxy.
"""
def __init__(self, *args, **kwargs):
self._socks_options = kwargs.pop("_socks_options")
super(SOCKSConnection, self).__init__(*args, **kwargs)
def _new_conn(self):
"""
... | SOCKSConnection |
python | mlflow__mlflow | mlflow/types/chat.py | {
"start": 4364,
"end": 4615
} | class ____(BaseModel):
"""
A tool definition passed to the chat completion API.
Ref: https://platform.openai.com/docs/guides/function-calling
"""
type: Literal["function"]
function: FunctionToolDefinition | None = None
| ChatTool |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/result.py | {
"start": 11957,
"end": 28295
} | class ____(InPlaceGenerative, Generic[_R]):
__slots__ = ()
_real_result: Optional[Result[Unpack[TupleAny]]] = None
_generate_rows: bool = True
_row_logging_fn: Optional[Callable[[Any], Any]]
_unique_filter_state: Optional[_UniqueFilterStateType] = None
_post_creational_filter: Optional[Callabl... | ResultInternal |
python | astropy__astropy | astropy/units/tests/test_quantity_non_ufuncs.py | {
"start": 2883,
"end": 3276
} | class ____(BasicTestSetup):
def check(self, func, *args, **kwargs):
out = func(self.q, *args, **kwargs)
expected = func(self.q.value, *args, *kwargs)
assert type(out) is type(expected)
if isinstance(expected, tuple):
assert all(np.all(o == x) for o, x in zip(out, expected... | NoUnitTestSetup |
python | chroma-core__chroma | chromadb/errors.py | {
"start": 2296,
"end": 2501
} | class ____(ChromaError):
@overrides
def code(self) -> int:
return 413
@classmethod
@overrides
def name(cls) -> str:
return "BatchSizeExceededError"
| BatchSizeExceededError |
python | getsentry__sentry | tests/sentry/dynamic_sampling/tasks/test_custom_rule_notifications.py | {
"start": 509,
"end": 4198
} | class ____(TestCase, SnubaTestCase):
def create_transaction(self) -> Event:
data = load_data("transaction")
return self.store_event(data, project_id=self.project.id)
def setUp(self) -> None:
super().setUp()
self.user = self.create_user(email="radu@sentry.io", username="raduw", n... | CustomRuleNotificationsTest |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/declarative_automation_tests/scenario_utils/asset_daemon_scenario.py | {
"start": 2270,
"end": 4400
} | class ____(NamedTuple):
"""Provides a convenient way to specify information about an AutoMaterializeRuleEvaluation
that is expected to exist within the context of a test.
Args:
rule (AutoMaterializeRule): The rule that will exist on the evaluation.
partitions (Optional[Sequence[str]]): The ... | AssetRuleEvaluationSpec |
python | readthedocs__readthedocs.org | readthedocs/api/v3/views.py | {
"start": 17218,
"end": 17901
} | class ____(
APIv3Settings,
NestedViewSetMixin,
ProjectQuerySetMixin,
FlexFieldsMixin,
ListModelMixin,
RetrieveModelMixin,
UpdateMixin,
UpdateModelMixin,
GenericViewSet,
):
model = Notification
lookup_field = "pk"
lookup_url_kwarg = "notification_pk"
serializer_class =... | NotificationsProjectViewSet |
python | great-expectations__great_expectations | tests/datasource/fluent/test_pandas_google_cloud_storage_datasource.py | {
"start": 924,
"end": 8101
} | class ____:
# noinspection PyMethodMayBeStatic,PyUnusedLocal
def list_blobs(
self,
bucket_or_name,
max_results=None,
prefix=None,
delimiter=None,
**kwargs,
) -> Iterator:
return iter([])
def _build_pandas_gcs_datasource(
gcs_options: Dict[str, An... | MockGCSClient |
python | Netflix__metaflow | test/data/__init__.py | {
"start": 398,
"end": 527
} | class ____(FlowSpec):
def __init__(self, name="FakeFlow", use_cli=False):
self.name = name
DO_TEST_RUN = False
| FakeFlow |
python | tensorflow__tensorflow | tensorflow/python/keras/losses.py | {
"start": 23124,
"end": 26361
} | class ____(LossFunctionWrapper):
"""Computes the crossentropy loss between the labels and predictions.
Use this crossentropy loss function when there are two or more label classes.
We expect labels to be provided in a `one_hot` representation. If you want to
provide labels as integers, please use `SparseCatego... | CategoricalCrossentropy |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefault2.py | {
"start": 1484,
"end": 1588
} | class ____[*Ts = T1]: ...
# This should generate an error because default must be unpacked tuple.
| ClassTs5 |
python | kamyu104__LeetCode-Solutions | Python/relative-sort-array.py | {
"start": 33,
"end": 334
} | class ____(object):
def relativeSortArray(self, arr1, arr2):
"""
:type arr1: List[int]
:type arr2: List[int]
:rtype: List[int]
"""
lookup = {v: i for i, v in enumerate(arr2)}
return sorted(arr1, key=lambda i: lookup.get(i, len(arr2)+i))
| Solution |
python | spulec__freezegun | tests/test_datetimes.py | {
"start": 21239,
"end": 21569
} | class ____(BaseInheritanceFreezableTests):
def test_time_is_not_frozen(self) -> None:
# In this class, time should not be frozen - and the below decorated
# class shouldn't affect that
self.assertNotEqual(datetime.date(2013, 4, 9), datetime.date.today())
@freeze_time('2013-04-09')
| UnfrozenInheritedTests |
python | facebook__pyre-check | client/commands/server_event.py | {
"start": 2924,
"end": 3486
} | class ____(Exception):
kind: ErrorKind
def __init__(self, exception_event: ServerException) -> None:
super().__init__(exception_event.message)
self.kind = exception_event.kind
def _parse_server_event(event_string: str) -> Event:
event = create_from_string(event_string)
if event is Non... | ServerStartException |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_connections.py | {
"start": 2710,
"end": 3102
} | class ____:
@pytest.fixture(autouse=True)
def setup(self) -> None:
clear_test_connections(False)
clear_db_connections(False)
clear_db_logs()
def teardown_method(self) -> None:
clear_db_connections()
def create_connection(self):
_create_connection()
def crea... | TestConnectionEndpoint |
python | pytorch__pytorch | torchgen/api/autograd.py | {
"start": 2153,
"end": 3279
} | class ____:
# The formula string (legit C++ expression).
# Note that special keywords such as "linear" or "element_wise" have been
# replaced by the automatically generated formula.
formula: str
# Name of the output arguments for which this formula calculates forward
# derivatives
var_names... | ForwardDerivative |
python | chroma-core__chroma | chromadb/test/property/strategies.py | {
"start": 2873,
"end": 3155
} | class ____(TypedDict):
"""
Represents the internal state of a state machine in hypothesis tests.
"""
ids: List[types.ID]
embeddings: types.Embeddings
metadatas: List[Optional[types.Metadata]]
documents: List[Optional[types.Document]]
| StateMachineRecordSet |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 9609,
"end": 9787
} | class ____(_ConfigUpdateModel):
bm25: Optional[_BM25ConfigUpdate]
cleanupIntervalSeconds: Optional[int]
stopwords: Optional[_StopwordsUpdate]
| _InvertedIndexConfigUpdate |
python | pytorch__pytorch | torch/distributions/one_hot_categorical.py | {
"start": 4433,
"end": 5028
} | class ____(OneHotCategorical):
r"""
Creates a reparameterizable :class:`OneHotCategorical` distribution based on the straight-
through gradient estimator from [1].
[1] Estimating or Propagating Gradients Through Stochastic Neurons for Conditional Computation
(Bengio et al., 2013)
"""
has_r... | OneHotCategoricalStraightThrough |
python | apache__airflow | providers/mysql/tests/unit/mysql/hooks/test_mysql.py | {
"start": 12236,
"end": 12579
} | class ____:
DEFAULT_AUTOCOMMIT = "default"
def __init__(self):
self._autocommit = self.DEFAULT_AUTOCOMMIT
@property
def autocommit(self):
return self._autocommit
@autocommit.setter
def autocommit(self, autocommit):
self._autocommit = autocommit
@pytest.mark.db_test
| MockMySQLConnectorConnection |
python | ray-project__ray | python/ray/_private/services.py | {
"start": 7955,
"end": 93871
} | class ____(subprocess.Popen):
if sys.platform == "win32":
def terminate(self):
if isinstance(self.stdin, io.IOBase):
self.stdin.close()
if self._use_signals:
self.send_signal(signal.CTRL_BREAK_EVENT)
else:
super(ConsolePope... | ConsolePopen |
python | pytorch__pytorch | torch/_dynamo/variables/misc.py | {
"start": 27368,
"end": 28227
} | class ____(VariableTracker):
# If the cell existed before Dynamo tracing started, this will be the
# VariableTracker that represents the cell content.
#
# Note that all mutation to the cell (i.e., its content) will be buffered in
# SideEffects, rather than being reflected here. One can think of
... | CellVariable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.